//  GeneralInfoViewController.mm

#import <objc/runtime.h>
#import "GeneralInfoViewController.h"
#import "APIClient.h"

@interface GeneralInfoViewController () <UIDocumentInteractionControllerDelegate, UIScrollViewDelegate>

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

@property (nonatomic, strong) UISegmentedControl *tabControl;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIStackView *ownerStack;
@property (nonatomic, strong) UIStackView *jointOwnersStack;
@property (nonatomic, strong) UIStackView *unitStack;
@property (nonatomic) NSLayoutConstraint *infoTop;
@property (nonatomic) NSLayoutConstraint *documentsTop;
@property (nonatomic) NSLayoutConstraint *formsTop;
@property (nonatomic) NSLayoutConstraint *infoBottom;
@property (nonatomic) NSLayoutConstraint *documentsBottom;
@property (nonatomic) NSLayoutConstraint *formsBottom;

// Sections for tabs
@property (nonatomic, strong) UIView *infoContainer;
@property (nonatomic, strong) UIView *documentsContainer;
@property (nonatomic, strong) UIView *formsContainer;

// Document collapsible sections
@property (nonatomic, strong) UIButton *generalDocHeader;
@property (nonatomic, strong) UIView *generalDocList;
@property (nonatomic, strong) UIButton *layoutDocHeader;
@property (nonatomic, strong) UIView *layoutDocList;
@property (nonatomic, strong) UIButton *unitDocHeader;
@property (nonatomic, strong) UIView *unitDocList;
@property (nonatomic, strong) UIStackView *generalDocStack;
@property (nonatomic, strong) UIStackView *layoutDocStack;
@property (nonatomic, strong) UIStackView *unitDocStack;

// Contact edit sheet
@property (nonatomic, strong) UIView *contactEditSheet;
@property (nonatomic, strong) UIView *contactDimView;

//api variables
@property (nonatomic, strong) NSArray *owners;
@property (nonatomic, strong) NSArray *jointOwners;
@property (nonatomic, strong) NSArray *generalDocuments;
@property (nonatomic, strong) NSArray *layoutDocuments;
@property (nonatomic, strong) NSArray *unitDocuments;
@property (nonatomic, strong) NSArray *forms;
@property (nonatomic, strong) NSString *layoutType;
@property (nonatomic, strong) NSString *layoutImage;
@property (nonatomic, strong) NSString *layoutThumbImage;
@property (nonatomic, strong) NSString *spaDate;
@property (nonatomic, strong) NSString *vpDate;
@property (nonatomic, strong) NSString *dlpStartDate;
@property (nonatomic, strong) NSString *dlpExpiryDate;
@property (nonatomic, strong) NSString *handoverDocument;
@property (nonatomic, strong) NSString *handoverStatus;
@property (nonatomic, strong) NSString *clearanceLetter;

@property (nonatomic, strong) UIStackView *formsStack;
@property (nonatomic, strong) NSLayoutConstraint *ownerSectionHeight;

typedef struct {
    UIButton *button;
    UIStackView *stack;
} SectionPair;

@end

@implementation GeneralInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.systemGroupedBackgroundColor;
    self.infoContainer = [[UIView alloc] init];
    self.documentsContainer = [[UIView alloc] init];
    self.formsContainer = [[UIView alloc] init];
    self.infoContainer.clipsToBounds = YES;
    self.documentsContainer.clipsToBounds = YES;
    self.formsContainer.clipsToBounds = YES;

    [self requestGeneralInfo];
    [self setupTopBar];
    [self setupTabControl];
    [self setupScrollView];
    [self buildInfoTab];
    [self buildDocumentsTab];
    [self buildFormsTab];
    [self setupContactEditSheet];

    [self switchTab:0];
}

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

    // Back button
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backButton setImage:[UIImage systemImageNamed:@"chevron.backward"]
                     forState:UIControlStateNormal];
    [self.backButton addTarget:self
                        action:@selector(onBack)
              forControlEvents:UIControlEventTouchUpInside];
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.backButton.tintColor = UIColor.whiteColor;
    [self.topBar addSubview:self.backButton];

    // Title
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = self.unitID ?: @"Unit Info";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.topBar addSubview:self.titleLabel];

    // Constraints
    [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:48],

        [self.backButton.leadingAnchor constraintEqualToAnchor:self.topBar.leadingAnchor constant:12],
        [self.backButton.centerYAnchor constraintEqualToAnchor:self.topBar.centerYAnchor],

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

#pragma mark - Tabs
- (void)setupTabControl {
    self.tabControl = [[UISegmentedControl alloc] initWithItems:@[@"Info", @"Document", @"Forms"]];
    self.tabControl.selectedSegmentIndex = 0;
    self.tabControl.translatesAutoresizingMaskIntoConstraints = NO;
    [self.tabControl addTarget:self
                        action:@selector(onTabChanged:)
              forControlEvents:UIControlEventValueChanged];

    [self.view addSubview:self.tabControl];

    [NSLayoutConstraint activateConstraints:@[
        [self.tabControl.topAnchor constraintEqualToAnchor:self.topBar.bottomAnchor constant:12],
        [self.tabControl.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        [self.tabControl.widthAnchor constraintEqualToConstant:260],
        [self.tabControl.heightAnchor constraintEqualToConstant:32],
    ]];
}

#pragma mark - Scroll View (Updated)
- (void)setupScrollView {
    // ScrollView
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.scrollView];

    [NSLayoutConstraint activateConstraints:@[
        [self.scrollView.topAnchor constraintEqualToAnchor:self.tabControl.bottomAnchor constant:12],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
    ]];

    // Content View inside scrollView
    self.contentView = [[UIView alloc] init];
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.contentView];

    [NSLayoutConstraint activateConstraints:@[
        [self.contentView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
        [self.contentView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor],
        [self.contentView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor],
        [self.contentView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor],
        [self.contentView.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor]
    ]];

    // Add the 3 tab containers
    [self.contentView addSubview:self.infoContainer];
    [self.contentView addSubview:self.documentsContainer];
    [self.contentView addSubview:self.formsContainer];

    // Horizontal constraints for all tabs
    for (UIView *container in @[self.infoContainer, self.documentsContainer, self.formsContainer]) {
        container.translatesAutoresizingMaskIntoConstraints = NO;
        [NSLayoutConstraint activateConstraints:@[
            [container.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor],
            [container.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor]
        ]];
    }

    //
    // ⭐ TOP Constraints (only ONE is active at a time)
    //
    self.infoTop = [self.infoContainer.topAnchor constraintEqualToAnchor:self.contentView.topAnchor];
    self.documentsTop = [self.documentsContainer.topAnchor constraintEqualToAnchor:self.contentView.topAnchor];
    self.formsTop = [self.formsContainer.topAnchor constraintEqualToAnchor:self.contentView.topAnchor];

    self.infoTop.active = YES;          // default visible tab
    self.documentsTop.active = NO;
    self.formsTop.active = NO;

    //
    // ⭐ BOTTOM Constraints (only ONE is active at a time)
    //
    self.infoBottom = [self.infoContainer.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor];
    self.documentsBottom = [self.documentsContainer.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor];
    self.formsBottom = [self.formsContainer.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor];

    self.infoBottom.active = YES;       // default tab
    self.documentsBottom.active = NO;
    self.formsBottom.active = NO;
}

#pragma mark - INFO TAB
- (void)buildInfoTab {
    // --- Header ---
    UILabel *header = [[UILabel alloc] init];
    header.text = @"Owner Details";
    header.font = [UIFont boldSystemFontOfSize:16];
    header.textColor = UIColor.darkGrayColor;
    header.translatesAutoresizingMaskIntoConstraints = NO;
    [self.infoContainer addSubview:header];

    // --- Main Owner Stack ---
    self.ownerStack = [[UIStackView alloc] init];
    self.ownerStack.axis = UILayoutConstraintAxisVertical;
    self.ownerStack.spacing = 8;
    self.ownerStack.translatesAutoresizingMaskIntoConstraints = NO;
    [self.infoContainer addSubview:self.ownerStack];

    // --- Joint Owners Title ---
    UILabel *jointTitle = [[UILabel alloc] init];
    jointTitle.text = @"Joint Owner Details";
    jointTitle.font = [UIFont boldSystemFontOfSize:16];
    jointTitle.textColor = UIColor.darkGrayColor;
    jointTitle.translatesAutoresizingMaskIntoConstraints = NO;
    [self.infoContainer addSubview:jointTitle];

    // --- Joint Owners Stack ---
    self.jointOwnersStack = [[UIStackView alloc] init];
    self.jointOwnersStack.axis = UILayoutConstraintAxisVertical;
    self.jointOwnersStack.spacing = 8;
    self.jointOwnersStack.translatesAutoresizingMaskIntoConstraints = NO;
    [self.infoContainer addSubview:self.jointOwnersStack];
  
    // unit title
    UILabel *unitTitle = [[UILabel alloc] init];
    unitTitle.text = @"Unit Info";
    unitTitle.font = [UIFont boldSystemFontOfSize:16];
    unitTitle.textColor = UIColor.darkGrayColor;
    unitTitle.translatesAutoresizingMaskIntoConstraints = NO;
    [self.infoContainer addSubview:unitTitle];
  
    // unit stack
    self.unitStack = [[UIStackView alloc] init];
    self.unitStack.axis = UILayoutConstraintAxisVertical;
    self.unitStack.spacing = 8;
    self.unitStack.translatesAutoresizingMaskIntoConstraints = NO;
    [self.infoContainer addSubview:self.unitStack];

    // --- Constraints ---
    [NSLayoutConstraint activateConstraints:@[
        [header.topAnchor constraintEqualToAnchor:self.infoContainer.topAnchor constant:12],
        [header.leadingAnchor constraintEqualToAnchor:self.infoContainer.leadingAnchor constant:12],

        [self.ownerStack.topAnchor constraintEqualToAnchor:header.bottomAnchor constant:12],
        [self.ownerStack.leadingAnchor constraintEqualToAnchor:self.infoContainer.leadingAnchor constant:16],
        [self.ownerStack.trailingAnchor constraintEqualToAnchor:self.infoContainer.trailingAnchor constant:-16],

        [jointTitle.topAnchor constraintEqualToAnchor:self.ownerStack.bottomAnchor constant:20],
        [jointTitle.leadingAnchor constraintEqualToAnchor:self.infoContainer.leadingAnchor constant:16],

        [self.jointOwnersStack.topAnchor constraintEqualToAnchor:jointTitle.bottomAnchor constant:12],
        [self.jointOwnersStack.leadingAnchor constraintEqualToAnchor:self.infoContainer.leadingAnchor constant:16],
        [self.jointOwnersStack.trailingAnchor constraintEqualToAnchor:self.infoContainer.trailingAnchor constant:-16],
        
        [unitTitle.topAnchor constraintEqualToAnchor:self.jointOwnersStack.bottomAnchor constant:20],
        [unitTitle.leadingAnchor constraintEqualToAnchor:self.infoContainer.leadingAnchor constant:16],
        
        [self.unitStack.topAnchor constraintEqualToAnchor:unitTitle.bottomAnchor constant:12],
        [self.unitStack.leadingAnchor constraintEqualToAnchor:self.infoContainer.leadingAnchor constant:16],
        [self.unitStack.trailingAnchor constraintEqualToAnchor:self.infoContainer.trailingAnchor constant:-16],
        [self.unitStack.bottomAnchor constraintEqualToAnchor:self.infoContainer.bottomAnchor constant:-20]
    ]];
    self.infoBottom = [self.infoContainer.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor];
    self.infoBottom.active = YES;
}

#pragma mark - DOCUMENTS TAB
- (void)buildDocumentsTab {
    self.documentsContainer.translatesAutoresizingMaskIntoConstraints = NO;

    // 1️⃣ Clear old sections
    for (UIView *v in self.documentsContainer.subviews) {
        [v removeFromSuperview];
    }
  
    NSLog(@"documentsContainer subviews: %@", self.documentsContainer.subviews);
    NSLog(@"BUILDING DOCUMENT TAB…");


    // 2️⃣ Helper to build a section container
    UIView* (^createSectionContainer)(NSString *, NSArray *) = ^UIView* (NSString *title, NSArray *items) {
        if (!items || items.count == 0) return nil;

        // Container
        UIView *container = [[UIView alloc] init];
        container.translatesAutoresizingMaskIntoConstraints = NO;
        container.backgroundColor = UIColor.clearColor;

        // Button (Header)
        UIButton *btn = [self collapsibleHeaderWithTitle:title];
        btn.translatesAutoresizingMaskIntoConstraints = NO;
        [container addSubview:btn];

        // Stack
        UIStackView *stack = [[UIStackView alloc] init];
        stack.axis = UILayoutConstraintAxisVertical;
        stack.spacing = 8;
        stack.translatesAutoresizingMaskIntoConstraints = NO;
        stack.backgroundColor = UIColor.whiteColor;
        stack.layer.cornerRadius = 10;
        stack.layoutMargins = UIEdgeInsetsMake(12, 12, 12, 12);
        stack.layoutMarginsRelativeArrangement = YES;
        stack.hidden = YES;
        [container addSubview:stack];

        // Bind stack to button
        objc_setAssociatedObject(btn, "sectionStack", stack, OBJC_ASSOCIATION_RETAIN);
        [btn addTarget:self action:@selector(toggleSection:) forControlEvents:UIControlEventTouchUpInside];

        // Add document labels
        for (NSDictionary *doc in items) {
            UILabel *lbl = [self label:doc[@"name"]];
            [stack addArrangedSubview:lbl];
        }

        // Constraints inside container
        [NSLayoutConstraint activateConstraints:@[
            [btn.topAnchor constraintEqualToAnchor:container.topAnchor constant:0],
            [btn.leadingAnchor constraintEqualToAnchor:container.leadingAnchor constant:0],
            [btn.trailingAnchor constraintEqualToAnchor:container.trailingAnchor constant:0],
            [btn.heightAnchor constraintEqualToConstant:44],

            [stack.topAnchor constraintEqualToAnchor:btn.bottomAnchor constant:4],
            [stack.leadingAnchor constraintEqualToAnchor:container.leadingAnchor],
            [stack.trailingAnchor constraintEqualToAnchor:container.trailingAnchor],
            [stack.bottomAnchor constraintEqualToAnchor:container.bottomAnchor]
        ]];

        // Save references for refresh if needed
        if ([title isEqualToString:@"General"]) self.generalDocStack = stack;
        if ([title isEqualToString:@"Layout"])  self.layoutDocStack  = stack;
        if ([title isEqualToString:@"Unit"])    self.unitDocStack    = stack;

        return container;
    };

    // 3️⃣ Create section containers
    UIView *generalContainer = createSectionContainer(@"General", self.generalDocuments);
    UIView *layoutContainer  = createSectionContainer(@"Layout", self.layoutDocuments);
    UIView *unitContainer    = createSectionContainer(@"Unit", self.unitDocuments);

    // 4️⃣ Add non-nil containers to documentsContainer
    NSMutableArray<UIView *> *sections = [NSMutableArray array];
    if (generalContainer) [sections addObject:generalContainer];
    if (layoutContainer)  [sections addObject:layoutContainer];
    if (unitContainer)    [sections addObject:unitContainer];

    UIView *previous = nil;
    for (UIView *section in sections) {
        [self.documentsContainer addSubview:section];

        [NSLayoutConstraint activateConstraints:@[
            [section.leadingAnchor constraintEqualToAnchor:self.documentsContainer.leadingAnchor constant:16],
            [section.trailingAnchor constraintEqualToAnchor:self.documentsContainer.trailingAnchor constant:-16],
        ]];

        if (previous) {
            [section.topAnchor constraintEqualToAnchor:previous.bottomAnchor constant:16].active = YES;
        } else {
            [section.topAnchor constraintEqualToAnchor:self.documentsContainer.topAnchor constant:16].active = YES;
        }

        previous = section;
    }

    // Pin last section to bottom so scroll view content size works
//    if (previous) {
//        [previous.bottomAnchor constraintEqualToAnchor:self.documentsContainer.bottomAnchor constant:-16].active = YES;
//    }
    self.documentsBottom = [self.documentsContainer.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor];
    self.documentsBottom.active = NO;
}

- (UIButton *)collapsibleHeaderWithTitle:(NSString *)title {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.backgroundColor = UIColor.blackColor;
    btn.layer.cornerRadius = 12;
    btn.clipsToBounds = YES;
    btn.translatesAutoresizingMaskIntoConstraints = NO;

    [btn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, 12, 0, 0);

    // Chevron icon using SF Symbols
    UIImageView *arrow = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"chevron.down"]];
    arrow.tintColor = UIColor.whiteColor;
    arrow.translatesAutoresizingMaskIntoConstraints = NO;

    [btn addSubview:arrow];

    // Attach arrow to the button object
    objc_setAssociatedObject(btn, "arrowView", arrow, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    [NSLayoutConstraint activateConstraints:@[
        [arrow.centerYAnchor constraintEqualToAnchor:btn.centerYAnchor],
        [arrow.trailingAnchor constraintEqualToAnchor:btn.trailingAnchor constant:-12],
        [arrow.heightAnchor constraintEqualToConstant:14],
        [arrow.widthAnchor constraintEqualToConstant:10]
    ]];

    return btn;
}

- (UIView *)collapsibleListPlaceholder {
    UIView *box = [[UIView alloc] init];
    box.backgroundColor = UIColor.whiteColor;
    box.layer.cornerRadius = 10;
    box.translatesAutoresizingMaskIntoConstraints = NO;
    self.ownerSectionHeight = [box.heightAnchor constraintEqualToConstant:0];
    self.ownerSectionHeight.active = YES; // collapsed at start
    return box;
}

#pragma mark - FORMS TAB
- (void)buildFormsTab {
    self.formsContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.formsContainer];

    self.formsStack = [[UIStackView alloc] init];
    self.formsStack.axis = UILayoutConstraintAxisVertical;
    self.formsStack.spacing = 8;
    self.formsStack.translatesAutoresizingMaskIntoConstraints = NO;
    [self.formsContainer addSubview:self.formsStack];

    [NSLayoutConstraint activateConstraints:@[
        [self.formsStack.topAnchor constraintEqualToAnchor:self.formsContainer.topAnchor constant:16],
        [self.formsStack.leadingAnchor constraintEqualToAnchor:self.formsContainer.leadingAnchor constant:16],
        [self.formsStack.trailingAnchor constraintEqualToAnchor:self.formsContainer.trailingAnchor constant:-16],
        [self.formsStack.bottomAnchor constraintEqualToAnchor:self.formsContainer.bottomAnchor constant:-16]
    ]];
    self.formsBottom = [self.formsContainer.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor];
    self.formsBottom.active = NO;
}

#pragma mark - Tab switching
- (void)onTabChanged:(UISegmentedControl *)sender {
    [self switchTab:sender.selectedSegmentIndex];
}

- (void)switchTab:(NSInteger)index {

    // Visibility
    self.infoContainer.hidden = index != 0;
    self.documentsContainer.hidden = index != 1;
    self.formsContainer.hidden = index != 2;

    // Only active tab receives interaction
    self.infoContainer.userInteractionEnabled = (index == 0);
    self.documentsContainer.userInteractionEnabled = (index == 1);
    self.formsContainer.userInteractionEnabled = (index == 2);

    // Disable all top constraints
    self.infoTop.active = NO;
    self.documentsTop.active = NO;
    self.formsTop.active = NO;

    // Disable all bottom constraints
    self.infoBottom.active = NO;
    self.documentsBottom.active = NO;
    self.formsBottom.active = NO;

    // Enable selected tab’s constraints
    if (index == 0) {
        self.infoTop.active = YES;
        self.infoBottom.active = YES;
    }
    else if (index == 1) {
        self.documentsTop.active = YES;
        self.documentsBottom.active = YES;
    }
    else if (index == 2) {
        self.formsTop.active = YES;
        self.formsBottom.active = YES;
    }

    // Animate layout change
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - Contact Edit Bottom Sheet
- (void)setupContactEditSheet {
    self.contactDimView = [[UIView alloc] init];
    self.contactDimView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    self.contactDimView.hidden = YES;
    self.contactDimView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.contactDimView];

    self.contactEditSheet = [[UIView alloc] init];
    self.contactEditSheet.backgroundColor = UIColor.whiteColor;
    self.contactEditSheet.layer.cornerRadius = 16;
    self.contactEditSheet.translatesAutoresizingMaskIntoConstraints = NO;
    self.contactEditSheet.hidden = YES;
    [self.view addSubview:self.contactEditSheet];

    [NSLayoutConstraint activateConstraints:@[
        [self.contactDimView.topAnchor constraintEqualToAnchor:self.view.topAnchor],
        [self.contactDimView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
        [self.contactDimView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.contactDimView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],

        [self.contactEditSheet.heightAnchor constraintEqualToConstant:300],
        [self.contactEditSheet.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.contactEditSheet.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.contactEditSheet.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
    ]];
}

#pragma mark - api
- (void)requestGeneralInfo {
    [APIClient requestGeneralInfo:^(BOOL success, NSDictionary *data, NSError *error) {
        if (error || !data) {
            NSLog(@"❌ General info error: %@", error.localizedDescription);
            return;
        }
        
        NSLog(@"📦 Received General Info Data: %@", data);
        NSDictionary *general = data[@"Data"];
        // 1️⃣ Write to file for debugging (your existing logic)
        NSString *plainText = [NSString stringWithFormat:@"%@", data];
        NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *filePath = [docsPath stringByAppendingPathComponent:@"generalData.txt"];
        [plainText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"📁 appointData saved as plain text to: %@", filePath);


        // 2️⃣ Safely extract each field
        self.owners = general[@"unit_owner"] ?: @[];
        self.jointOwners = general[@"joint_unit_owner"] ?: @[];

        self.layoutDocuments = general[@"owner_document_phase"] ?: @[];
        self.generalDocuments = general[@"owner_document_project"] ?: @[];
        
        NSArray *rawUnitDocs = general[@"owner_document_unit"];
        NSMutableArray *unitDocs = rawUnitDocs ? [rawUnitDocs mutableCopy] : [NSMutableArray array];

        // clearance_letter_attachment is a DICTIONARY
        NSDictionary *clearanceDict = general[@"clearance_letter_attachment"];

        if (clearanceDict &&
            [clearanceDict isKindOfClass:[NSDictionary class]] &&
            [clearanceDict[@"file"] isKindOfClass:[NSString class]] &&
            [clearanceDict[@"file"] length] > 0)
        {
            [unitDocs addObject:clearanceDict];
        }

        self.unitDocuments = unitDocs;

        self.forms = general[@"contactless_form"] ?: @[];

        self.layoutType = general[@"layout"] ?: @"";
        self.layoutImage = general[@"image"] ?: @"";
        self.layoutThumbImage = general[@"thumb_image"] ?: @"";

        self.spaDate = general[@"spa_date"] ?: @"";
        self.vpDate = general[@"vp_date"] ?: general[@"vp_date"][@"date"] ?: @"";

        self.dlpStartDate = general[@"dlp_start_date"] ?: @"";
        self.dlpExpiryDate = general[@"dlp_expiry_date"] ?: @"";

        self.handoverDocument = general[@"handover_document"] ?: @"";
        self.handoverStatus = general[@"handover_status"];
        self.clearanceLetter = general[@"clearance_letter_attachment"] ?: @"";
  
        // 3️⃣ Update UI on main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            [self refreshUI];
        });
    }];
}

- (void)refreshUI {
    NSLog(@"refreshUI called");

    // ------------------------
    // 0️⃣ CLEAR EXISTING UI
    // ------------------------

    // Clear Owners
    for (UIView *v in self.ownerStack.arrangedSubviews) {
        [self.ownerStack removeArrangedSubview:v];
        [v removeFromSuperview];
    }

    // Clear Joint Owners
    for (UIView *v in self.jointOwnersStack.arrangedSubviews) {
        [self.jointOwnersStack removeArrangedSubview:v];
        [v removeFromSuperview];
    }

    // Clear Unit Info
    for (UIView *v in self.unitStack.arrangedSubviews) {
        [self.unitStack removeArrangedSubview:v];
        [v removeFromSuperview];
    }


    // ------------------------
    // 1️⃣ OWNERS SECTION
    // ------------------------

    NSArray *ownerTitles = @[@"Name", @"Email", @"Contact No."];
    CGFloat maxTitleWidth = 0;

    for (NSString *title in ownerTitles) {
        CGSize size = [title sizeWithAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:14]}];
        maxTitleWidth = MAX(maxTitleWidth, size.width);
    }
    maxTitleWidth += 6;


    UIStackView* (^OwnerCard)(NSDictionary *) = ^UIStackView* (NSDictionary *owner) {

        UIStackView *card = [[UIStackView alloc] init];
        card.axis = UILayoutConstraintAxisVertical;
        card.spacing = 8;
        card.backgroundColor = UIColor.whiteColor;
        card.layer.cornerRadius = 10;
        card.layoutMargins = UIEdgeInsetsMake(12, 12, 12, 12);
        card.layoutMarginsRelativeArrangement = YES;
        card.translatesAutoresizingMaskIntoConstraints = NO;

        UIStackView* (^Row)(NSString *, NSString *) = ^UIStackView* (NSString *title, NSString *value) {

            UIStackView *row = [[UIStackView alloc] init];
            row.axis = UILayoutConstraintAxisHorizontal;
            row.spacing = 8;
            row.alignment = UIStackViewAlignmentFill;

            UILabel *titleLabel = [[UILabel alloc] init];
            titleLabel.text = [NSString stringWithFormat:@"%@:", title];
            titleLabel.font = [UIFont boldSystemFontOfSize:14];
            [titleLabel.widthAnchor constraintEqualToConstant:maxTitleWidth].active = YES;

            UILabel *valueLabel = [[UILabel alloc] init];
            valueLabel.text = value ?: @"-";
            valueLabel.font = [UIFont systemFontOfSize:14];
            valueLabel.numberOfLines = 0;

            [row addArrangedSubview:titleLabel];
            [row addArrangedSubview:valueLabel];

            return row;
        };

        NSString *name = owner[@"name"] ?: @"-";
        NSString *email = owner[@"email"] ?: @"-";
        NSString *contact = owner[@"contact"] ?: @"-";

        [card addArrangedSubview:Row(@"Name", name)];
        [card addArrangedSubview:Row(@"Email", email)];
        [card addArrangedSubview:Row(@"Contact No.", contact)];

        return card;
    };

    // Add Owner cards
    for (NSDictionary *owner in self.owners) {
        [self.ownerStack addArrangedSubview:OwnerCard(owner)];
    }

    // Add Joint Owner cards
    for (NSDictionary *owner in self.jointOwners) {
        [self.jointOwnersStack addArrangedSubview:OwnerCard(owner)];
    }

    // ------------------------
    // 2️⃣ UNIT INFO SECTION
    // ------------------------
    NSString *projectName = self.unitName ?: @"-";
    NSString *projectId = self.unitID ?: @"-";
    NSString *layoutType = self.layoutType ?: @"-";
    NSString *expiryDate = self.dlpExpiryDate ?: @"-";
    NSString *layoutImageURL = self.layoutImage ?: @"";
    NSString *handoverDocURL = self.handoverDocument ?: @"";

    UIStackView *unitCard = [[UIStackView alloc] init];
    unitCard.axis = UILayoutConstraintAxisVertical;
    unitCard.spacing = 12;
    unitCard.backgroundColor = UIColor.whiteColor;
    unitCard.layer.cornerRadius = 10;
    unitCard.layoutMargins = UIEdgeInsetsMake(12, 12, 12, 12);
    unitCard.layoutMarginsRelativeArrangement = YES;
    unitCard.translatesAutoresizingMaskIntoConstraints = NO;

    UIStackView* (^TitleRow)(NSString*, UIView*) = ^UIStackView* (NSString *title, UIView *valueView) {

        UIStackView *row = [[UIStackView alloc] init];
        row.axis = UILayoutConstraintAxisHorizontal;
        row.spacing = 8;
        row.alignment = UIStackViewAlignmentTop;   // better for multiline values
        row.translatesAutoresizingMaskIntoConstraints = NO;

        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.text = [NSString stringWithFormat:@"%@:", title];
        titleLabel.font = [UIFont boldSystemFontOfSize:14];
        titleLabel.numberOfLines = 0;
        titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
      
        // 🔥 Apply same alignment width as Owners
        [titleLabel.widthAnchor constraintEqualToConstant:maxTitleWidth].active = YES;

        [row addArrangedSubview:titleLabel];
        [row addArrangedSubview:valueView];

        return row;
    };


    // Project Name
    [unitCard addArrangedSubview:TitleRow(@"Project Name", [self label:projectName])];

    // Unit No
    [unitCard addArrangedSubview:TitleRow(@"Unit No.", [self label:projectId])];

    // Layout Type
    [unitCard addArrangedSubview:TitleRow(@"Layout Type", [self label:layoutType])];

    // Layout Image
    if (layoutImageURL.length > 0) {
        UIImageView *imgView = [[UIImageView alloc] init];
        imgView.translatesAutoresizingMaskIntoConstraints = NO;
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imgView.layer.cornerRadius = 8;
        imgView.clipsToBounds = YES;
        imgView.userInteractionEnabled = YES;

        [imgView.widthAnchor constraintEqualToConstant:120].active = YES;
        [imgView.heightAnchor constraintEqualToConstant:80].active = YES;

        NSURL *url = [NSURL URLWithString:layoutImageURL];
        if (url) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                NSData *data = [NSData dataWithContentsOfURL:url];
                if (data) {
                    UIImage *img = [UIImage imageWithData:data];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        imgView.image = img;
                    });
                }
            });
        }

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

        [unitCard addArrangedSubview:TitleRow(@"Layout Image", imgView)];
    }

    // DLP Expiry
    [unitCard addArrangedSubview:TitleRow(@"DLP Expiry Date", [self label:expiryDate])];

    // Handover PDF
    if (handoverDocURL.length > 0) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        [btn setImage:[UIImage systemImageNamed:@"doc.text"] forState:UIControlStateNormal];
        btn.tintColor = UIColor.systemBlueColor;
        
        objc_setAssociatedObject(btn, "pdfURL", handoverDocURL, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        
        // Set a custom filename for the button PDF
        NSString *pdfName = @"HandoverDocument"; // change this as needed
        objc_setAssociatedObject(btn, "pdfName", pdfName, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        
        [btn addTarget:self action:@selector(openRemotePDFButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

        [unitCard addArrangedSubview:TitleRow(@"Handover Document", btn)];
    }

    [self.unitStack addArrangedSubview:unitCard];


    // ------------------------
    // DOCUMENTS TAB (Rebuild)
    // ------------------------
    [self refreshDocumentsUI];
  
    // ------------------------
    // 4️⃣ FORMS TAB
    // ------------------------

    for (UIView *v in self.formsStack.arrangedSubviews) {
        [self.formsStack removeArrangedSubview:v];
        [v removeFromSuperview];
    }

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"dd MMM yyyy, hh:mm a";
    df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];

    NSDateFormatter *displayFormatter = [[NSDateFormatter alloc] init];
    displayFormatter.dateStyle = NSDateFormatterMediumStyle;

    NSArray *sortedForms =
        [self.forms sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *f1, NSDictionary *f2) {
            NSDate *d1 = [df dateFromString:f1[@"datetime"] ?: @"01 Jan 1970, 12:00 AM"];
            NSDate *d2 = [df dateFromString:f2[@"datetime"] ?: @"01 Jan 1970, 12:00 AM"];
            return [d2 compare:d1];
        }];

    for (NSDictionary *form in sortedForms) {
        NSString *name = form[@"name"] ?: @"-";
        NSString *dateStr = form[@"datetime"] ?: @"";
        NSDate *date = [df dateFromString:dateStr];
        NSString *file = form[@"file"];

        UIView *card = [[UIView alloc] init];
        card.backgroundColor = UIColor.whiteColor;
        card.layer.cornerRadius = 8;

        UIStackView *labelStack = [[UIStackView alloc] init];
        labelStack.axis = UILayoutConstraintAxisVertical;
        labelStack.spacing = 4;

        UILabel *nameLabel = [[UILabel alloc] init];
        nameLabel.text = name;
        nameLabel.font = [UIFont boldSystemFontOfSize:14];
        [labelStack addArrangedSubview:nameLabel];

        UILabel *dateLabel = [[UILabel alloc] init];
        dateLabel.text = date ? [NSString stringWithFormat:@"Submitted on %@", [displayFormatter stringFromDate:date]]
                              : @"Submitted on -";
        dateLabel.font = [UIFont systemFontOfSize:12];
        [labelStack addArrangedSubview:dateLabel];

        [card addSubview:labelStack];
        labelStack.translatesAutoresizingMaskIntoConstraints = NO;
        [NSLayoutConstraint activateConstraints:@[
            [labelStack.topAnchor constraintEqualToAnchor:card.topAnchor constant:8],
            [labelStack.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
            [labelStack.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-12],
            [labelStack.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-8]
        ]];

        if (file && ![file isKindOfClass:[NSNull class]] && ![file isEqualToString:@"<null>"]) {
            objc_setAssociatedObject(card, "pdfURL", file, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            
            // Set a custom filename, e.g., based on the file or a label
            NSString *pdfName = name; // change this as needed
            objc_setAssociatedObject(card, "pdfName", pdfName, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            
            UITapGestureRecognizer *tap =
                [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openPDFFromView:)];
            [card addGestureRecognizer:tap];
        }

        [self.formsStack addArrangedSubview:card];
        [card.heightAnchor constraintGreaterThanOrEqualToConstant:50].active = YES;
    }
}

- (void)refreshDocumentsUI {
    // 1. Clear old content
    for (UIView *v in self.documentsContainer.subviews) {
        [v removeFromSuperview];
    }

    SectionPair general = [self buildDocumentSection:@"General" items:self.generalDocuments];
    SectionPair layout  = [self buildDocumentSection:@"Layout" items:self.layoutDocuments];
    SectionPair unit    = [self buildDocumentSection:@"Unit" items:self.unitDocuments];

    NSArray *sections = @[
        general.button ? @[general.button, general.stack] : @[],
        layout.button  ? @[layout.button,  layout.stack]  : @[],
        unit.button    ? @[unit.button,    unit.stack]    : @[]
    ];

    UIView *previous = nil;

    for (NSArray *pair in sections) {
        if (pair.count == 0) continue;

        UIButton *btn = pair[0];
        UIStackView *stack = pair[1];

        [self.documentsContainer addSubview:btn];
        [self.documentsContainer addSubview:stack];

        [NSLayoutConstraint activateConstraints:@[
            [btn.leadingAnchor constraintEqualToAnchor:self.documentsContainer.leadingAnchor constant:16],
            [btn.trailingAnchor constraintEqualToAnchor:self.documentsContainer.trailingAnchor constant:-16],
            [btn.heightAnchor constraintEqualToConstant:44],
            [btn.topAnchor constraintEqualToAnchor:previous ? previous.bottomAnchor : self.documentsContainer.topAnchor
                                                        constant:16],

            [stack.topAnchor constraintEqualToAnchor:btn.bottomAnchor constant:4],
            [stack.leadingAnchor constraintEqualToAnchor:btn.leadingAnchor],
            [stack.trailingAnchor constraintEqualToAnchor:btn.trailingAnchor],
        ]];

        previous = stack;
    }

    if (previous) {
        [NSLayoutConstraint activateConstraints:@[
            [previous.bottomAnchor constraintEqualToAnchor:self.documentsContainer.bottomAnchor constant:-30]
        ]];
    }
}

- (SectionPair)buildDocumentSection:(NSString *)title items:(NSArray *)items {
    if (!items || items.count == 0) {
        SectionPair empty = { nil, nil };
        return empty;
    }

    UIButton *btn = [self collapsibleHeaderWithTitle:title];
    btn.translatesAutoresizingMaskIntoConstraints = NO;

    UIStackView *stack = [[UIStackView alloc] init];
    stack.axis = UILayoutConstraintAxisVertical;
    stack.spacing = 8;
    stack.hidden = NO;
    stack.translatesAutoresizingMaskIntoConstraints = NO;
    stack.backgroundColor = UIColor.whiteColor;
    stack.layer.cornerRadius = 10;
    stack.layoutMargins = UIEdgeInsetsMake(12, 12, 12, 12);
    stack.layoutMarginsRelativeArrangement = YES;

    objc_setAssociatedObject(btn, "sectionStack", stack, OBJC_ASSOCIATION_RETAIN);
    [btn addTarget:self action:@selector(toggleSection:) forControlEvents:UIControlEventTouchUpInside];

    UIImageView *arrow = objc_getAssociatedObject(btn, "arrowView");
    if (arrow) {
        arrow.transform = CGAffineTransformMakeRotation(M_PI);
    }

    for (NSDictionary *doc in items) {
        NSString *fileURL = doc[@"file"];
        NSString *name = doc[@"name"] ?: @"Document";

        UIView *card = [[UIView alloc] init];
        card.backgroundColor = UIColor.whiteColor;
        card.layer.cornerRadius = 8;
        card.layer.borderWidth = 0.5;
        card.layer.borderColor = UIColor.lightGrayColor.CGColor;
        card.translatesAutoresizingMaskIntoConstraints = NO;

        UILabel *lbl = [[UILabel alloc] init];
        lbl.text = name;
        lbl.font = [UIFont systemFontOfSize:15];
        lbl.numberOfLines = 0;

        [card addSubview:lbl];
        lbl.translatesAutoresizingMaskIntoConstraints = NO;

        [NSLayoutConstraint activateConstraints:@[
            [lbl.topAnchor constraintEqualToAnchor:card.topAnchor constant:10],
            [lbl.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:12],
            [lbl.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-12],
            [lbl.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-10],
        ]];

        if ([fileURL length] > 0) {
            objc_setAssociatedObject(card, "pdfURL", fileURL, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            objc_setAssociatedObject(card, "pdfName", name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

            UITapGestureRecognizer *tap =
                [[UITapGestureRecognizer alloc] initWithTarget:self
                                                        action:@selector(openPDFFromView:)];
            card.userInteractionEnabled = YES;
            [card addGestureRecognizer:tap];
        }

        [stack addArrangedSubview:card];
    }

    SectionPair pair = { btn, stack };
    return pair;
}

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

- (void)toggleSection:(UIButton *)sender {
    UIStackView *stack = objc_getAssociatedObject(sender, "sectionStack");
    if (!stack) return;

    UIImageView *arrow = objc_getAssociatedObject(sender, "arrowView");
    if (!arrow) return;

    BOOL isCollapsed = stack.isHidden;

    // Animate the change
    [UIView animateWithDuration:0.3 animations:^{
        stack.hidden = !isCollapsed;
        // Rotate the arrow: down = collapsed, up = expanded
        arrow.transform = isCollapsed ? CGAffineTransformMakeRotation(M_PI) : CGAffineTransformIdentity;
        // Force layout update so scroll view resizes properly
        [self.documentsContainer layoutIfNeeded];
    }];
}

- (UILabel *)label:(NSString *)text {
    UILabel *lb = [[UILabel alloc] init];
    lb.text = text;
    lb.font = [UIFont systemFontOfSize:16];
    return lb;
}

-(void) formTapped {
  NSLog(@"Form tapped");
}

// Download remote PDF to temp file and open with UIDocumentInteractionController
- (void)openRemotePDF:(NSString *)remoteURLString fileName:(NSString *)fileName {
    if (!remoteURLString || [remoteURLString isEqualToString:@""]) return;
    if (!fileName || [fileName isEqualToString:@""]) fileName = @"Document";

    // Ensure the filename ends with .pdf
    if (![fileName.pathExtension.lowercaseString isEqualToString:@"pdf"]) {
        fileName = [fileName stringByAppendingPathExtension:@"pdf"];
    }

    NSURL *remoteURL = [NSURL URLWithString:remoteURLString];
    if (!remoteURL) return;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError *downloadError = nil;
        NSData *pdfData = [NSData dataWithContentsOfURL:remoteURL options:0 error:&downloadError];

        if (!pdfData || downloadError) {
            NSLog(@"Failed to download PDF: %@", downloadError);
            return;
        }

        // Save to temporary file with custom name
        NSString *tmpPath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
        NSURL *fileURL = [NSURL fileURLWithPath:tmpPath];

        BOOL success = [pdfData writeToURL:fileURL atomically:YES];
        if (!success) {
            NSLog(@"Failed to save PDF to temp file");
            return;
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            UIDocumentInteractionController *docController =
                [UIDocumentInteractionController interactionControllerWithURL:fileURL];
            docController.delegate = self;
            [docController presentPreviewAnimated:YES];
        });
    });
}

- (void)openPDFFromView:(UITapGestureRecognizer *)gesture {
    NSString *url = objc_getAssociatedObject(gesture.view, "pdfURL");
    NSString *fileName = objc_getAssociatedObject(gesture.view, "pdfName"); // optional custom name
    [self openRemotePDF:url fileName:fileName ?: @"Document"];
}

- (void)openRemotePDFButtonTapped:(UIButton *)sender {
    NSString *url = objc_getAssociatedObject(sender, "pdfURL");
    NSString *fileName = objc_getAssociatedObject(sender, "pdfName"); // optional custom name
    [self openRemotePDF:url fileName:fileName ?: @"Document"];
}

// UIDocumentInteractionController delegate
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {
    return self;
}

- (void)showFullImage:(UITapGestureRecognizer *)sender {
    UIImageView *imageView = (UIImageView *)sender.view;
    if (!imageView.image) return; // Nothing to show

    // Full screen scroll view
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    scrollView.backgroundColor = [UIColor blackColor];
    scrollView.minimumZoomScale = 1.0;
    scrollView.maximumZoomScale = 3.0;
    scrollView.delegate = self;
    scrollView.tag = 999; // optional for reference

    // Full-screen image view
    UIImageView *fullImageView = [[UIImageView alloc] initWithImage:imageView.image];
    fullImageView.contentMode = UIViewContentModeScaleAspectFit;
    fullImageView.frame = scrollView.bounds;
    fullImageView.userInteractionEnabled = YES;

    [scrollView addSubview:fullImageView];

    // Add tap to dismiss
    UITapGestureRecognizer *dismissTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissFullImage:)];
    [scrollView addGestureRecognizer:dismissTap];

    // Add to main view
    [self.view addSubview:scrollView];
}

- (void)dismissFullImage:(UITapGestureRecognizer *)sender {
    [sender.view removeFromSuperview];
}

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    // Return the image view inside the scroll view
    return scrollView.subviews.firstObject;
}

@end
