//  HistoryViewController.mm

#import "HistoryViewController.h"
#import "APIClient.h"
#import "CalendarView.h"
#import "NSDate+CalendarHelpers.h"
#import "AddInfoViewController.h"
#import "ImageCacheHelper.h"

typedef NS_ENUM(NSInteger, TimelineRowType) {
    TimelineRowTypeDate,
    TimelineRowTypeUpdate,
    TimelineRowTypeStatus
};

@interface TimelineRow : NSObject
@property TimelineRowType type;
@property NSDictionary *item;   // update or status source
@property NSString *dateKey;
@end

@implementation TimelineRow
@end

@interface HistoryViewController () <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *addInfoButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *historyItems;
@property (nonatomic, strong) NSString *userName;
@property (nonatomic, strong) NSArray<TimelineRow *> *timelineRows;

@end

@implementation HistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
    // --- Base background (replaces systemGroupedBackground) ---
    self.view.backgroundColor = [UIColor whiteColor];
    
    // --- Header bar color ---
    self.headerView.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0]; // teal
    self.titleLabel.textColor = [UIColor whiteColor];
    
    // --- TableView styling ---
    self.tableView.backgroundColor = [UIColor colorWithWhite:0.97 alpha:1.0]; // very light gray
    self.tableView.separatorColor = [UIColor colorWithWhite:0.9 alpha:1.0];
    
    // --- Section header label colors ---
    self.tableView.sectionIndexColor = [UIColor darkGrayColor];
    
    // --- Optional: consistent scroll indicator style ---
    self.tableView.indicatorStyle = UIScrollViewIndicatorStyleBlack;
    
    // --- Tint / global accent color (used for buttons, etc) ---
    self.view.tintColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
  
    [self setupHeader];
    [self setupTableView];
    [self handleIssues];
  
    NSLog(@"📦 Data received by History:\n projectName: %@\n projectCode: %@\n status: %@\n unitName: %@\n reference: %@",
        self.projectName,
        self.projectCode,
        self.status,
        self.unitName,
        self.reference);
}

#pragma mark - Header
- (void)setupHeader {
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = [UIColor colorWithRed:0.0 green:0.43 blue:0.55 alpha:1.0];
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerView];

    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.backButton setImage:[UIImage systemImageNamed:@"chevron.left"] forState:UIControlStateNormal];
    self.backButton.tintColor = UIColor.whiteColor;
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.backButton addTarget:self action:@selector(backTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.backButton];

    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"Issue History";
    self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.headerView addSubview:self.titleLabel];

    self.addInfoButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.addInfoButton setImage:[UIImage systemImageNamed:@"document.badge.plus"] forState:UIControlStateNormal];
    self.addInfoButton.tintColor = UIColor.whiteColor;
    self.addInfoButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.addInfoButton addTarget:self action:@selector(addInfoTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.addInfoButton];

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

        [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:16],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],
        
        [self.addInfoButton.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor constant:-16],
        [self.addInfoButton.centerYAnchor constraintEqualToAnchor:self.headerView.centerYAnchor],

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

#pragma mark - TableView
- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero
                                                  style:UITableViewStylePlain];
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.opaque = YES;
    self.tableView.estimatedRowHeight = 200;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self.view addSubview:self.tableView];

    [NSLayoutConstraint activateConstraints:@[
        [self.tableView.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor],
        [self.tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
    ]];
}

#pragma mark - API request/response
- (void)handleIssues {
    [APIClient requestHistory:self.issueID
                   completion:^(BOOL success, NSDictionary *data, NSError *error) {
        if (error) return;

        NSArray *mainData = data[@"Data"];
        if (!mainData || ![mainData isKindOfClass:[NSArray class]]) return;

        NSMutableArray *rows = [NSMutableArray array];
        NSArray *reversed = [[mainData reverseObjectEnumerator] allObjects];

        NSString *lastDate = nil;
        NSString *lastStatus = nil;

        NSMutableArray *currentDayUpdates = [NSMutableArray array];
        NSDictionary *currentDayLastItem = nil;

        for (NSDictionary *item in reversed) {
            NSString *datePost = item[@"date_post"] ?: @"";
            NSString *dateOnly = [[[datePost componentsSeparatedByString:@","]
                                    firstObject] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

            // New day
            if (![dateOnly isEqualToString:lastDate]) {
                // Add previous day’s updates
                for (NSDictionary *upd in currentDayUpdates) {
                    TimelineRow *updateRow = [TimelineRow new];
                    updateRow.type = TimelineRowTypeUpdate;
                    updateRow.item = upd;
                    updateRow.dateKey = lastDate;
                    [rows addObject:updateRow];
                }

                // Add previous day’s status if changed
                if (currentDayLastItem && ![currentDayLastItem[@"status_external"] isEqualToString:lastStatus]) {
                    TimelineRow *statusRow = [TimelineRow new];
                    statusRow.type = TimelineRowTypeStatus;
                    statusRow.item = currentDayLastItem;
                    statusRow.dateKey = lastDate;
                    [rows addObject:statusRow];

                    lastStatus = currentDayLastItem[@"status_external"];
                }

                // Add date header
                TimelineRow *dateRow = [TimelineRow new];
                dateRow.type = TimelineRowTypeDate;
                dateRow.dateKey = dateOnly;
                [rows addObject:dateRow];

                lastDate = dateOnly;
                [currentDayUpdates removeAllObjects];
            }

            [currentDayUpdates addObject:item];
            currentDayLastItem = item;
        }

        // Add last day’s updates + status
        for (NSDictionary *upd in currentDayUpdates) {
            TimelineRow *updateRow = [TimelineRow new];
            updateRow.type = TimelineRowTypeUpdate;
            updateRow.item = upd;
            updateRow.dateKey = lastDate;
            [rows addObject:updateRow];
        }
        if (currentDayLastItem && ![currentDayLastItem[@"status_external"] isEqualToString:lastStatus]) {
            TimelineRow *statusRow = [TimelineRow new];
            statusRow.type = TimelineRowTypeStatus;
            statusRow.item = currentDayLastItem;
            statusRow.dateKey = lastDate;
            [rows addObject:statusRow];
        }

        self.timelineRows = rows;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }];
}

#pragma mark - Table Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TimelineRow *row = self.timelineRows[indexPath.row];

    switch (row.type) {
        case TimelineRowTypeDate:
            return 30;

        case TimelineRowTypeStatus:
            return 60;
        
        case TimelineRowTypeUpdate:
            return UITableViewAutomaticDimension;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
    TimelineRow *row = self.timelineRows[indexPath.row];
    
    switch (row.type) {

        case TimelineRowTypeDate:
            return [self dateCellForRow:row];

        case TimelineRowTypeUpdate:
            return [self updateCellForRow:row tableView:tableView indexPath:indexPath];

        case TimelineRowTypeStatus:
            return [self statusCellForRow:row tableView:tableView indexPath:indexPath];
    }
}

- (UITableViewCell *)dateCellForRow:(TimelineRow *)row {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.backgroundColor = UIColor.clearColor;

    UILabel *label = [[UILabel alloc] init];
    label.text = row.dateKey;
    label.font = [UIFont boldSystemFontOfSize:15];
    label.textColor = UIColor.darkGrayColor;
    label.translatesAutoresizingMaskIntoConstraints = NO;

    [cell.contentView addSubview:label];

    [NSLayoutConstraint activateConstraints:@[
        [label.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:16],
        [label.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor constant:8],
        [label.bottomAnchor constraintEqualToAnchor:cell.contentView.bottomAnchor constant:-8],
    ]];

    return cell;
}

- (UITableViewCell *)updateCellForRow:(TimelineRow *)row tableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
      static NSString *identifier = @"HistoryCell";
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor clearColor];
            cell.contentView.backgroundColor = [UIColor clearColor];
            
            UIView *card = [[UIView alloc] init];
            card.tag = 100;
            card.layer.cornerRadius = 12;
            card.backgroundColor = UIColor.whiteColor;
            card.layer.shadowColor = [UIColor blackColor].CGColor;
            card.layer.shadowOpacity = 0.1;
            card.layer.shadowOffset = CGSizeMake(0, 1);
            card.layer.shadowRadius = 2;
            card.translatesAutoresizingMaskIntoConstraints = NO;
            [cell.contentView addSubview:card];

            UILabel *userLabel = [[UILabel alloc] init];
            userLabel.tag = 101;
            userLabel.font = [UIFont boldSystemFontOfSize:14];
            userLabel.translatesAutoresizingMaskIntoConstraints = NO;
            [card addSubview:userLabel];
          
            UIView *separator = [[UIView alloc] init];
            separator.tag = 104; // unique tag
            separator.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1]; // light gray
            separator.translatesAutoresizingMaskIntoConstraints = NO;
            [card addSubview:separator];

            UIImageView *avatarView = [[UIImageView alloc] init];
            avatarView.tag = 103;
            avatarView.layer.cornerRadius = 16;
            avatarView.clipsToBounds = YES;
            avatarView.contentMode = UIViewContentModeScaleAspectFill;
            avatarView.translatesAutoresizingMaskIntoConstraints = NO;
            [card addSubview:avatarView];

            UILabel *remarkLabel = [[UILabel alloc] init];
            remarkLabel.tag = 102;
            remarkLabel.numberOfLines = 0;
            remarkLabel.font = [UIFont systemFontOfSize:14];
            remarkLabel.textColor = UIColor.darkGrayColor;
            remarkLabel.translatesAutoresizingMaskIntoConstraints = NO;
            [card addSubview:remarkLabel];

            UIScrollView *thumbScroll = [[UIScrollView alloc] init];
            thumbScroll.tag = 105;
            thumbScroll.showsHorizontalScrollIndicator = NO;
            thumbScroll.translatesAutoresizingMaskIntoConstraints = NO;
            [card addSubview:thumbScroll];
          
            NSLayoutConstraint *thumbHeight =
                [thumbScroll.heightAnchor constraintEqualToConstant:124];
            thumbHeight.active = YES;
            thumbHeight.identifier = @"thumbHeight";

            UIView *lineTop = [[UIView alloc] init];
            lineTop.tag = 200; // timelineLineTop
            lineTop.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
            lineTop.translatesAutoresizingMaskIntoConstraints = NO;
            [cell.contentView addSubview:lineTop];

            UIView *lineBottom = [[UIView alloc] init];
            lineBottom.tag = 201; // timelineLineBottom
            lineBottom.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
            lineBottom.translatesAutoresizingMaskIntoConstraints = NO;
            [cell.contentView addSubview:lineBottom];

            UILabel *timeLabel = [[UILabel alloc] init];
            timeLabel.tag = 211;
            timeLabel.backgroundColor = [UIColor blackColor];
            timeLabel.textColor = [UIColor whiteColor];
            timeLabel.font = [UIFont boldSystemFontOfSize:12];
            timeLabel.textAlignment = NSTextAlignmentCenter;
            timeLabel.layer.cornerRadius = 10;
            timeLabel.clipsToBounds = YES;
            timeLabel.translatesAutoresizingMaskIntoConstraints = NO;
            [cell.contentView addSubview:timeLabel];

            [NSLayoutConstraint activateConstraints:@[
            [card.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor constant:8],
            [card.leadingAnchor constraintEqualToAnchor:timeLabel.trailingAnchor constant:16],
            [card.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor constant:-16],
            [card.bottomAnchor constraintEqualToAnchor:cell.contentView.bottomAnchor constant:-20],

            [avatarView.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
            [avatarView.topAnchor constraintEqualToAnchor:card.topAnchor constant:12],
            [avatarView.widthAnchor constraintEqualToConstant:36],
            [avatarView.heightAnchor constraintEqualToConstant:36],

            [userLabel.centerYAnchor constraintEqualToAnchor:avatarView.centerYAnchor],
            [userLabel.leadingAnchor constraintEqualToAnchor:avatarView.trailingAnchor constant:12],
            [userLabel.trailingAnchor constraintLessThanOrEqualToAnchor:card.trailingAnchor constant:-12],
            
            [separator.topAnchor constraintEqualToAnchor:avatarView.bottomAnchor constant:12],
            [separator.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
            [separator.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-12],
            [separator.heightAnchor constraintEqualToConstant:1],

            [remarkLabel.topAnchor constraintEqualToAnchor:separator.bottomAnchor constant:12],
            [remarkLabel.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
            [remarkLabel.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-12],

            [thumbScroll.topAnchor constraintEqualToAnchor:remarkLabel.bottomAnchor constant:10],
            [thumbScroll.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
            [thumbScroll.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-12],
            [thumbScroll.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-12],
            
            // Shared X position
            [lineTop.widthAnchor constraintEqualToConstant:2],
            [lineBottom.widthAnchor constraintEqualToConstant:2],

            [lineTop.centerXAnchor constraintEqualToAnchor:timeLabel.centerXAnchor],
            [lineBottom.centerXAnchor constraintEqualToAnchor:timeLabel.centerXAnchor],

            // Top line: from top of cell → center of circle
            [lineTop.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor],
            [lineTop.bottomAnchor constraintEqualToAnchor:timeLabel.topAnchor],

            // Bottom line: from center of circle → bottom of cell
            [lineBottom.topAnchor constraintEqualToAnchor:timeLabel.bottomAnchor],
            [lineBottom.bottomAnchor constraintEqualToAnchor:cell.contentView.bottomAnchor],

            // Align time capsule left of circle
            [timeLabel.centerXAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:60],
            [timeLabel.centerYAnchor constraintEqualToAnchor:card.centerYAnchor],
            [timeLabel.widthAnchor constraintEqualToConstant:88],
            [timeLabel.heightAnchor constraintEqualToConstant:28],
        ]];
      }

      NSDictionary *item = row.item;
      UILabel *userLabel = [cell viewWithTag:101];
      UILabel *remarkLabel = [cell viewWithTag:102];
      UIScrollView *thumbScroll = [cell viewWithTag:105];

      NSDictionary *user = item[@"user"];
      self.userName = [self safeString:user[@"name"]];
      NSString *rawRemark = [[self safeString:item[@"remarks"]]
                             stringByTrimmingCharactersInSet:
                             NSCharacterSet.whitespaceAndNewlineCharacterSet];
      NSString *remark = rawRemark.length > 0 ? rawRemark : @"-";
      NSString *datePost = [self safeString:item[@"date_post"]];
      NSArray *images = item[@"image"];
      NSLayoutConstraint *thumbHeight = nil;
      for (NSLayoutConstraint *c in thumbScroll.constraints) {
          if ([c.identifier isEqualToString:@"thumbHeight"]) {
              thumbHeight = c;
              break;
          }
      }
  
      UIImageView *avatarView = [cell viewWithTag:103];
      NSString *avatar = @"";
      if ([item[@"user"] isKindOfClass:[NSDictionary class]]) {
          avatar = [self safeString:item[@"user"][@"avatar"] ?: item[@"avatar"]];
      }
      if (avatar.length > 0) {
          NSURL *url = [NSURL URLWithString:avatar];
          [ImageCacheHelper loadImageWithURL:url completion:^(UIImage *image) {
              if (image) {
                  avatarView.image = image;
              } else {
                  avatarView.image = [UIImage systemImageNamed:@"person.circle"]; // fallback
              }
          }];
      } else {
          avatarView.image = [UIImage systemImageNamed:@"person.circle"];
      }

      BOOL hasImages = [images isKindOfClass:[NSArray class]] && images.count > 0;

      CGFloat thumbHeightValue = 0;
      if (hasImages) {
          thumbHeightValue = 124;
      }
      thumbHeight.constant = thumbHeightValue;
      thumbScroll.hidden = (thumbHeightValue == 0);

      UILabel *timeLabel = [cell viewWithTag:211];
      UIView *lineTop = [cell.contentView viewWithTag:200];
      UIView *lineBottom = [cell.contentView viewWithTag:201];
  
      TimelineRow *prev = indexPath.row > 0 ? self.timelineRows[indexPath.row - 1] : nil;
      TimelineRow *next = indexPath.row + 1 < self.timelineRows.count ? self.timelineRows[indexPath.row + 1] : nil;

      BOOL sameDateAbove = prev && [prev.dateKey isEqualToString:row.dateKey];
      BOOL sameDateBelow = next && [next.dateKey isEqualToString:row.dateKey];

      lineTop.hidden = !sameDateAbove;
      lineBottom.hidden = !sameDateBelow;

      // Extract the time portion after the comma
      NSString *timePart = @"";
      NSArray *parts = [datePost componentsSeparatedByString:@","];
      if (parts.count > 1) {
          timePart = [parts.lastObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
      }
      timeLabel.text = timePart.length > 0 ? timePart : @"--";

      userLabel.text = self.userName;
      remarkLabel.text = remark;

      // 🧹 Remove previous image views (since cells are reused)
      for (UIView *subview in thumbScroll.subviews) {
          [subview removeFromSuperview];
      }

      // 🖼️ Add thumbnails
      UIView *card = [cell viewWithTag:100];

      // Force layout so frame is correct
      [card layoutIfNeeded];

      // Card inner width (12 padding left + right)
      CGFloat availableWidth = card.bounds.size.width - 24;

      NSInteger count = images.count;
      CGFloat spacing = 8;

      NSInteger columns = 1;
      if (count == 2) {
          columns = 2;
      } else if (count >= 3) {
          columns = 3;
      }

      CGFloat thumbWidth =
          (availableWidth - (spacing * (columns - 1))) / columns;
      CGFloat thumbSide = thumbWidth; // square thumbnails

      CGFloat x = 0;

      for (NSInteger i = 0; i < images.count; i++) {
          NSDictionary *imgDict = images[i];
          NSString *thumbURL = imgDict[@"thumb_image"];
          if (thumbURL.length == 0) continue;

          CGRect frame = CGRectMake(x, 0, thumbSide, thumbSide);
          UIImageView *thumbView = [[UIImageView alloc] initWithFrame:frame];

          thumbView.layer.cornerRadius = 8;
          thumbView.clipsToBounds = YES;
          thumbView.contentMode = UIViewContentModeScaleAspectFill;
          thumbView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
          thumbView.userInteractionEnabled = YES;

          UITapGestureRecognizer *tap =
              [[UITapGestureRecognizer alloc] initWithTarget:self
                                                      action:@selector(handleImageTap:)];

          [thumbView addGestureRecognizer:tap];

          // store full image URL (or thumb if that's all you have)
          thumbView.accessibilityHint = imgDict[@"image"];

          [thumbScroll addSubview:thumbView];

          NSURL *url = [NSURL URLWithString:thumbURL];
          [ImageCacheHelper loadImageWithURL:url completion:^(UIImage *image) {
              if (image) thumbView.image = image;
          }];

          x += thumbSide + spacing;
      }

      CGFloat contentWidth = availableWidth;
      thumbScroll.contentSize = CGSizeMake(contentWidth, thumbSide);

      // update height constraint
      thumbHeight.constant = hasImages ? thumbSide : 0;
      thumbScroll.hidden = !hasImages;

      return cell;
}

- (UITableViewCell *)statusCellForRow:(TimelineRow *)row
                            tableView:(UITableView *)tableView
                            indexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.backgroundColor = UIColor.clearColor;

    NSDictionary *item = row.item;
    NSString *status = [self safeString:item[@"status_external"]];
    NSString *hex = [self safeString:item[@"status_ex_color"]];
  
    UIView *lineTop = [[UIView alloc] init];
    lineTop.tag = 200;
    lineTop.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
    lineTop.translatesAutoresizingMaskIntoConstraints = NO;
    [cell.contentView addSubview:lineTop];

    UIView *lineBottom = [[UIView alloc] init];
    lineBottom.tag = 201;
    lineBottom.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
    lineBottom.translatesAutoresizingMaskIntoConstraints = NO;
    [cell.contentView addSubview:lineBottom];
  
    UILabel *timeLabel = [[UILabel alloc] init];
    timeLabel.tag = 211;
    timeLabel.backgroundColor = [UIColor blackColor];
    timeLabel.textColor = [UIColor whiteColor];
    timeLabel.font = [UIFont boldSystemFontOfSize:12];
    timeLabel.textAlignment = NSTextAlignmentCenter;
    timeLabel.layer.cornerRadius = 10;
    timeLabel.clipsToBounds = YES;
    timeLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [cell.contentView addSubview:timeLabel];

    UILabel *pill = [[UILabel alloc] init];
    pill.text = status;
    pill.textColor = UIColor.whiteColor;
    pill.backgroundColor = [self colorFromHex:hex];
    pill.font = [UIFont boldSystemFontOfSize:14];
    pill.textAlignment = NSTextAlignmentCenter;
    pill.translatesAutoresizingMaskIntoConstraints = NO;

    [cell.contentView addSubview:pill];

    [NSLayoutConstraint activateConstraints:@[
        [timeLabel.centerXAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor constant:60],
        [timeLabel.centerYAnchor constraintEqualToAnchor:cell.centerYAnchor],
        [timeLabel.widthAnchor constraintEqualToConstant:88],
        [timeLabel.heightAnchor constraintEqualToConstant:28],

        [lineTop.widthAnchor constraintEqualToConstant:2],
        [lineBottom.widthAnchor constraintEqualToConstant:2],

        [lineTop.centerXAnchor constraintEqualToAnchor:timeLabel.centerXAnchor],
        [lineBottom.centerXAnchor constraintEqualToAnchor:timeLabel.centerXAnchor],

        [lineTop.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor],
        [lineTop.bottomAnchor constraintEqualToAnchor:timeLabel.topAnchor],

        [lineBottom.topAnchor constraintEqualToAnchor:timeLabel.bottomAnchor],
        [lineBottom.bottomAnchor constraintEqualToAnchor:cell.contentView.bottomAnchor],
      
        [pill.centerYAnchor constraintEqualToAnchor:timeLabel.centerYAnchor],
        [pill.leadingAnchor constraintEqualToAnchor:timeLabel.trailingAnchor constant:16],
        [pill.widthAnchor constraintGreaterThanOrEqualToConstant:128],
        [pill.heightAnchor constraintEqualToConstant:60],
    ]];
    pill.layer.cornerRadius = 60 / 2;
    pill.clipsToBounds = YES;
  
    TimelineRow *prev = indexPath.row > 0 ? self.timelineRows[indexPath.row - 1] : nil;
    TimelineRow *next = indexPath.row + 1 < self.timelineRows.count ? self.timelineRows[indexPath.row + 1] : nil;

    BOOL sameDateAbove = prev && [prev.dateKey isEqualToString:row.dateKey];
    BOOL sameDateBelow = next && [next.dateKey isEqualToString:row.dateKey];

    lineTop.hidden = !sameDateAbove;
    lineBottom.hidden = !sameDateBelow;
  
    NSString *datePost = [self safeString:item[@"date_post"]];
    NSString *timePart = @"";
    NSArray *parts = [datePost componentsSeparatedByString:@","];
    if (parts.count > 1) {
        timePart = [parts.lastObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    timeLabel.text = timePart.length > 0 ? timePart : @"--";

    return cell;
}

#pragma mark - Utils
- (UIColor *)colorFromHex:(NSString *)hex {
    unsigned int rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hex];
    if ([hex hasPrefix:@"#"]) scanner.scanLocation = 1;
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0
                           green:((rgbValue & 0x00FF00) >> 8)/255.0
                            blue:(rgbValue & 0x0000FF)/255.0
                           alpha:1.0];
}

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

- (void)addInfoTapped {
    NSLog(@"➕ Add Info tapped");
    AddInfoViewController *vc = [[AddInfoViewController alloc] init];
    vc.issueID = self.issueID;
    vc.planID = self.planID;
    vc.status = self.status;
    vc.unitName = self.unitName;
    vc.reference = self.reference;
    vc.userName = self.userName;
    vc.projectCode = self.projectCode;
    vc.projectName = self.projectName;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - helper
- (NSString *)safeString:(id)value {
    if ([value isKindOfClass:[NSString class]]) return value;
    if ([value isKindOfClass:[NSNumber class]]) return [value stringValue];
    return @"–";
}

- (void)handleImageTap:(UITapGestureRecognizer *)sender {
    UIImageView *tappedImageView = (UIImageView *)sender.view;
    if (!tappedImageView.image) return;

    // Overlay
    UIView *overlay = [[UIView alloc] initWithFrame:self.view.bounds];
    overlay.backgroundColor = [UIColor colorWithWhite:0 alpha:0.95];
    overlay.alpha = 0;
    overlay.tag = 900;
    overlay.userInteractionEnabled = YES;
    [self.view addSubview:overlay];

    // Scroll view for zoom/pan
    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:overlay.bounds];
    scroll.minimumZoomScale = 1.0;
    scroll.maximumZoomScale = 4.0;
    scroll.delegate = self;
    scroll.showsVerticalScrollIndicator = NO;
    scroll.showsHorizontalScrollIndicator = NO;
    scroll.backgroundColor = UIColor.clearColor;
    scroll.tag = 901;
    [overlay addSubview:scroll];

    // Full image
    UIImageView *fullImageView = [[UIImageView alloc] initWithFrame:scroll.bounds];
    fullImageView.contentMode = UIViewContentModeScaleAspectFit;
    fullImageView.image = tappedImageView.image;
    fullImageView.userInteractionEnabled = YES;
    fullImageView.tag = 902;
    [scroll addSubview:fullImageView];

    // Double-tap gesture to zoom
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    doubleTap.numberOfTapsRequired = 2;
    [fullImageView addGestureRecognizer:doubleTap];

    // Single-tap to dismiss overlay
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeFullImage)];
    singleTap.numberOfTapsRequired = 1;
    [overlay addGestureRecognizer:singleTap];

    // Prevent single tap from firing when double-tap occurs
    [singleTap requireGestureRecognizerToFail:doubleTap];

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

// UIScrollViewDelegate method
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    if (scrollView.tag == 901) {
        return [scrollView viewWithTag:902]; // the UIImageView inside
    }
    return nil;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    if (scrollView.tag != 901) return;

    UIImageView *imageView = [scrollView viewWithTag:902];
    CGFloat offsetX = MAX((scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5, 0.0);
    CGFloat offsetY = MAX((scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5, 0.0);
    imageView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                   scrollView.contentSize.height * 0.5 + offsetY);
}

- (void)handleDoubleTap:(UITapGestureRecognizer *)gesture {
    UIScrollView *scroll = (UIScrollView *)gesture.view.superview;
    if (!scroll) return;

    if (scroll.zoomScale > 1.0) {
        [scroll setZoomScale:1.0 animated:YES];
    } else {
        CGPoint pointInView = [gesture locationInView:gesture.view];
        CGFloat newZoomScale = scroll.maximumZoomScale;
        CGFloat w = scroll.bounds.size.width / newZoomScale;
        CGFloat h = scroll.bounds.size.height / newZoomScale;
        CGFloat x = pointInView.x - w/2.0;
        CGFloat y = pointInView.y - h/2.0;
        CGRect rectToZoom = CGRectMake(x, y, w, h);
        [scroll zoomToRect:rectToZoom animated:YES];
    }
}

- (void)closeFullImage {
    UIView *overlay = [self.view viewWithTag:900];
    if (!overlay) return;

    [UIView animateWithDuration:0.25 animations:^{
        overlay.alpha = 0;
    } completion:^(BOOL finished) {
        [overlay removeFromSuperview];
    }];
}

@end
