// PlanViewController.mm
#import "PlanViewController.h"
#import "DetailsViewController.h"
#import "AddIssueAPIClient.h"

@interface PlanViewController ()

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIButton *helpButton;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIImageView *planImageView;
@property (nonatomic, strong) NSString *selectedLocation;
@property (nonatomic, strong) NSDictionary *unitPlanData;
@property (nonatomic, strong) NSArray *locations;
@property (nonatomic, strong) NSString *planImageURL;
@property (nonatomic, assign) CGFloat planWidth;
@property (nonatomic, assign) CGFloat planHeight;

@end

@implementation PlanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    NSLog(@"PlanViewController loaded");

    // Create UI elements (but don’t assign final frames yet)
    [self createHeader];
    [self createScrollView];
  
    [self fetchInitialData];
    [self.view bringSubviewToFront:self.headerView];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self.view bringSubviewToFront:self.headerView];
  
    static BOOL hasRenderedLocations = NO;
    if (!hasRenderedLocations && self.planImageView.image && self.locations.count > 0) {
        hasRenderedLocations = YES;
        [self renderAllLocations:self.locations];
    }
}

- (void)fetchInitialData {
    NSLog(@"🌐 Fetching Unit Plan data...");

    [AddIssueAPIClient fetchGetUnitPlan:^(NSDictionary *data, NSError *error) {
        if (error) {
            NSLog(@"❌ Unit Plan fetch failed: %@", error.localizedDescription);
            return;
        }

        NSLog(@"✅ Raw Unit Plan response received");
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
        NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *filePath = [docsPath stringByAppendingPathComponent:@"getUnitPlan.txt"];
        [jsonData writeToFile:filePath atomically:YES];
        NSLog(@"📁 UnitPlan saved to %@", filePath);

        // 🔍 Parse JSON
        NSDictionary *appData = data[@"AppData"];
        if (![appData[@"status"] isEqualToString:@"success"]) {
            NSLog(@"⚠️ Server returned non-success status: %@", appData[@"message"]);
            return;
        }

        NSArray *mainData = data[@"Data"];
        if (mainData.count == 0) {
            NSLog(@"⚠️ No unit plan data found");
            return;
        }

        // Store main plan object
        self.unitPlanData = mainData.firstObject;
        self.locations = self.unitPlanData[@"location"];

        if (self.locations.count == 0) {
            NSLog(@"⚠️ No locations found in plan");
            return;
        }

        // ✅ Extract plan dimensions and image URL
        NSDictionary *firstLocation = self.locations.firstObject;
        NSArray *issues = firstLocation[@"issue"];
        if (issues.count == 0) {
            NSLog(@"⚠️ No issues found under first location");
            return;
        }

        NSDictionary *firstIssue = issues.firstObject;
        NSString *widthStr = [NSString stringWithFormat:@"%@", firstIssue[@"plan_width"]];
        NSString *heightStr = [NSString stringWithFormat:@"%@", firstIssue[@"plan_height"]];
        self.planWidth = [widthStr floatValue];
        self.planHeight = [heightStr floatValue];
        self.planImageURL = firstIssue[@"plan_image"];

        NSLog(@"📐 Plan dimensions: width = %f, height = %f", self.planWidth, self.planHeight);
        NSLog(@"🗺 Found %lu locations", (unsigned long)self.locations.count);
        NSLog(@"🖼 Plan image URL: %@", self.planImageURL);

        // Update UI on main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            [self displayPlanImage];
            [self debugPrintAllIssues];
        });
    }];
}

- (void)displayPlanImage {
    if (!self.planImageURL || self.planImageURL.length == 0) {
        NSLog(@"⚠️ No plan image URL found");
        return;
    }

    NSURL *url = [NSURL URLWithString:self.planImageURL];
    if (!url) {
        NSLog(@"⚠️ Invalid plan image URL: %@", self.planImageURL);
        return;
    }

    NSLog(@"⬇️ Downloading plan image from %@", self.planImageURL);
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url
                                                             completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error || !data) {
            NSLog(@"❌ Failed to download plan image: %@", error.localizedDescription);
            return;
        }

        UIImage *image = [UIImage imageWithData:data];
        if (!image) {
            NSLog(@"⚠️ Could not decode image data");
            return;
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            self.planImageView.image = image;
            [self.scrollView setZoomScale:1.0 animated:NO];
            [self.view setNeedsLayout];
            [self.view layoutIfNeeded];
            [self renderAllLocations:self.locations];
            NSLog(@"✅ Plan image displayed successfully");
        });
    }];
    [task resume];
}


#pragma mark - UI Creation
- (void)createHeader {
    // 🟩 Status bar background
    UIView *statusBarBackground = [[UIView alloc] init];
    statusBarBackground.backgroundColor = [UIColor colorWithRed:0/255.0
                                                          green:109/255.0
                                                           blue:141/255.0
                                                          alpha:1];
    statusBarBackground.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:statusBarBackground];
    
    // 🟦 Header background
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = statusBarBackground.backgroundColor;
    self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.headerView];

    // 🔙 Back button
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.backButton.translatesAutoresizingMaskIntoConstraints = NO;
    UIImage *backImage = [[UIImage systemImageNamed:@"chevron.left"]
                          imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [self.backButton setImage:backImage forState:UIControlStateNormal];
    self.backButton.tintColor = UIColor.whiteColor;
    [self.backButton addTarget:self
                        action:@selector(handleBack)
              forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.backButton];

    // ❓ Help button
    self.helpButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.helpButton.translatesAutoresizingMaskIntoConstraints = NO;
    UIImage *helpImage = [[UIImage systemImageNamed:@"questionmark.circle"]
                           imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [self.helpButton setImage:helpImage forState:UIControlStateNormal];
    self.helpButton.tintColor = UIColor.whiteColor;
    [self.helpButton addTarget:self
                        action:@selector(showTutorial)
              forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:self.helpButton];

    // 🏷 Title label (project name)
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.titleLabel.text = self.projectName ?: @"Plan Viewer";
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.headerView addSubview:self.titleLabel];

    // 🧩 Subtitle label (project code)
    UILabel *subtitleLabel = [[UILabel alloc] init];
    subtitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    subtitleLabel.text = self.projectCode ?: @"";
    subtitleLabel.textColor = [UIColor colorWithWhite:1.0 alpha:0.8];
    subtitleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    subtitleLabel.textAlignment = NSTextAlignmentCenter;
    [self.headerView addSubview:subtitleLabel];

    // ✅ Constraints
    UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
    CGFloat headerHeight = 110.0; // header height

    [NSLayoutConstraint activateConstraints:@[
        // Status bar background
        [statusBarBackground.topAnchor constraintEqualToAnchor:self.view.topAnchor],
        [statusBarBackground.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [statusBarBackground.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [statusBarBackground.bottomAnchor constraintEqualToAnchor:safe.topAnchor],

        // Header
        [self.headerView.topAnchor constraintEqualToAnchor:safe.topAnchor],
        [self.headerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.headerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.headerView.heightAnchor constraintEqualToConstant:headerHeight],

        // Back button
        [self.backButton.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:8],
        [self.backButton.topAnchor constraintEqualToAnchor:self.headerView.topAnchor constant:4],
        [self.backButton.widthAnchor constraintEqualToConstant:44],
        [self.backButton.heightAnchor constraintEqualToConstant:44],

        // Help button
        [self.helpButton.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor constant:-8],
        [self.helpButton.centerYAnchor constraintEqualToAnchor:self.backButton.centerYAnchor],
        [self.helpButton.widthAnchor constraintEqualToConstant:44],
        [self.helpButton.heightAnchor constraintEqualToConstant:44],

        // Title label (below buttons, left-aligned)
        [self.titleLabel.topAnchor constraintEqualToAnchor:self.backButton.bottomAnchor constant:4],
        [self.titleLabel.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor constant:16],
        [self.titleLabel.trailingAnchor constraintLessThanOrEqualToAnchor:self.helpButton.leadingAnchor constant:-8],

        // Subtitle (below title, left-aligned)
        [subtitleLabel.topAnchor constraintEqualToAnchor:self.titleLabel.bottomAnchor constant:2],
        [subtitleLabel.leadingAnchor constraintEqualToAnchor:self.titleLabel.leadingAnchor],
        [subtitleLabel.trailingAnchor constraintLessThanOrEqualToAnchor:self.helpButton.leadingAnchor constant:-8],
    ]];
}

- (void)loadPlanImageFromURL:(NSString *)urlString {
    NSURL *url = [NSURL URLWithString:urlString];
    if (!url) return;

    NSURLSessionDataTask *task = [[NSURLSession sharedSession]
        dataTaskWithURL:url
      completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"❌ Failed to load image: %@", error);
            return;
        }
        UIImage *image = [UIImage imageWithData:data];
        if (image) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.planImageView.image = image;
                NSLog(@"🖼 Plan image loaded successfully");
            });
        }
    }];
    [task resume];
}

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

- (void)handleUnitPlanResponse:(NSDictionary *)data {
    NSLog(@"🧩 Handling Unit Plan response...");

    NSDictionary *appData = data[@"AppData"];
    NSArray *mainData = data[@"Data"];

    // 🧱 Step 1 — Check for maintenance
    if ([appData[@"error_code"] integerValue] == 503) {
        NSLog(@"⚠️ Maintenance mode");
        [self showAlertWithTitle:@"Maintenance Mode" message:@"System under maintenance. Please try again later."];
        return;
    }

    // 🧱 Step 2 — If status is success
    if ([appData[@"status"] isEqualToString:@"success"]) {
        if (mainData.count > 0) {
            NSDictionary *unitPlan = mainData.firstObject;
            self.unitPlanData = unitPlan;

            // ✅ Extract and store plan dimensions (ensure they’re numeric)
            NSString *widthStr = [NSString stringWithFormat:@"%@", unitPlan[@"plan_width"]];
            NSString *heightStr = [NSString stringWithFormat:@"%@", unitPlan[@"plan_height"]];
            self.planWidth = [widthStr floatValue];
            self.planHeight = [heightStr floatValue];

            NSLog(@"📏 planWidth = %f, planHeight = %f", self.planWidth, self.planHeight);

            // 🧱 Safety check
            if (self.planWidth <= 0 || self.planHeight <= 0) {
                NSLog(@"⚠️ Invalid plan dimensions — overlays may not render correctly.");
            }

            // Save JSON for debugging
            NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
            NSString *filePath = [docsPath stringByAppendingPathComponent:@"unitPlanParsed.json"];
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:unitPlan options:NSJSONWritingPrettyPrinted error:nil];
            [jsonData writeToFile:filePath atomically:YES];
            NSLog(@"📁 Parsed unit plan saved to %@", filePath);

            // 🖼 Step 3 — Load image if available
            NSString *planImageURL = unitPlan[@"plan_image"];
            if (planImageURL.length > 0) {
                [self loadPlanImageFromURL:planImageURL];
            } else {
                NSLog(@"⚠️ No plan_image found in response");
            }

            // ✅ Update title
            NSString *unitName = unitPlan[@"unit_name"] ?: @"No name";
            dispatch_async(dispatch_get_main_queue(), ^{
                self.titleLabel.text = unitName;
            });
        }
    } else {
        // 🧱 Step 4 — Handle error response
        NSString *message = appData[@"message"] ?: @"Unknown error.";
        if ([message isEqualToString:@"user_not_found"]) {
            [self showAlertWithTitle:@"Session Expired" message:@"Please log in again."];
        } else {
            [self showAlertWithTitle:@"Error" message:message];
        }
    }
}

- (void)createScrollView {
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.delegate = (id<UIScrollViewDelegate>)self;
    self.scrollView.minimumZoomScale = 1.0;
    self.scrollView.maximumZoomScale = 5.0;
    self.scrollView.bouncesZoom = YES;
    self.scrollView.alwaysBounceVertical = YES;
    self.scrollView.alwaysBounceHorizontal = YES;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.scrollView];

    self.planImageView = [[UIImageView alloc] init];
    self.planImageView.contentMode = UIViewContentModeScaleAspectFit;
    self.planImageView.backgroundColor = [UIColor whiteColor];
    self.planImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addSubview:self.planImageView];

    // ✅ Scroll view constraints (below header)
    [NSLayoutConstraint activateConstraints:@[
        [self.scrollView.topAnchor constraintEqualToAnchor:self.headerView.bottomAnchor],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
    ]];

    // ✅ Image view constraints (fills scroll view)
    [NSLayoutConstraint activateConstraints:@[
        [self.planImageView.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor],
        [self.planImageView.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor],
        [self.planImageView.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor],
        [self.planImageView.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor],
        [self.planImageView.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor],
        [self.planImageView.heightAnchor constraintEqualToAnchor:self.scrollView.heightAnchor],
    ]];
}

- (void)renderLocation:(NSDictionary *)locationData onImageView:(UIImageView *)planImageView {
    if (!planImageView.image) return;

    CGRect imageRect = [self imageRectInImageView:planImageView];
    CGFloat displayedWidth = imageRect.size.width;
    CGFloat displayedHeight = imageRect.size.height;

    NSArray *issues = locationData[@"issue"];
    NSLog(@"Total issues: %lu", (unsigned long)issues.count);

    NSLog(@"planWidth: %f, planHeight: %f", self.planWidth, self.planHeight);

    CGFloat scaleX = displayedWidth / self.planWidth;
    CGFloat scaleY = displayedHeight / self.planHeight;

    NSArray *points = locationData[@"points"];
    if (!points || points.count == 0) {
        NSLog(@"⚠️ No points found for location %@", locationData[@"id"]);
        return;
    }

    UIBezierPath *path = [UIBezierPath bezierPath];

    for (int i = 0; i < points.count; i++) {
        NSDictionary *point = points[i];
        CGFloat x = imageRect.origin.x + [point[@"x"] doubleValue] * scaleX;
        CGFloat y = imageRect.origin.y + [point[@"y"] doubleValue] * scaleY;

        if (i == 0) [path moveToPoint:CGPointMake(x, y)];
        else [path addLineToPoint:CGPointMake(x, y)];

        // 🔵 Visual dot marker
//        UIView *dot = [[UIView alloc] initWithFrame:CGRectMake(x - 2, y - 2, 4, 4)];
//        dot.backgroundColor = [UIColor blueColor];
//        dot.layer.cornerRadius = 2;
//        [planImageView addSubview:dot];

        NSLog(@"📍 Point %d -> x=%f, y=%f", i, x, y);

        if (x < imageRect.origin.x || y < imageRect.origin.y ||
            x > imageRect.origin.x + imageRect.size.width ||
            y > imageRect.origin.y + imageRect.size.height) {
            NSLog(@"⚠️ Point %d is out of bounds!", i);
        }
    }

    [path closePath];

    CAShapeLayer *polygonLayer = [CAShapeLayer layer];
    polygonLayer.path = path.CGPath;
    polygonLayer.fillColor = UIColor.clearColor.CGColor;
    polygonLayer.strokeColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.3].CGColor;
    polygonLayer.lineWidth = 2.0;

    [planImageView.layer addSublayer:polygonLayer];
}

- (CGRect)imageRectInImageView:(UIImageView *)imageView {
    CGSize imageSize = imageView.image.size;
    CGSize viewSize = imageView.bounds.size;
    CGFloat scale = MIN(viewSize.width / imageSize.width, viewSize.height / imageSize.height);
    CGFloat width = imageSize.width * scale;
    CGFloat height = imageSize.height * scale;
    CGFloat x = (viewSize.width - width) / 2.0;
    CGFloat y = (viewSize.height - height) / 2.0;
    return CGRectMake(x, y, width, height);
}

- (void)renderAllLocations:(NSArray *)locations {
    for (NSDictionary *locationData in locations) {
        [self renderLocation:locationData onImageView:self.planImageView];
    }
}

- (UIColor *)colorFromHex:(NSString *)hexString {
    unsigned int rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:[hexString stringByReplacingOccurrencesOfString:@"#" withString:@""]];
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue >> 16) & 0xFF) / 255.0
                           green:((rgbValue >> 8) & 0xFF) / 255.0
                            blue:(rgbValue & 0xFF) / 255.0
                           alpha:1.0];
}


- (void)handleNextScreen {
  [self showAddIssuePopup];
}

- (void)showAddIssuePopup {
    NSLog(@"🟢 Showing Add Issue popup");

    // Background dim view
    UIView *overlay = [[UIView alloc] initWithFrame:self.view.bounds];
    overlay.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    overlay.alpha = 0.0;
    overlay.tag = 999; // so we can find and remove it later
    [self.view addSubview:overlay];

    // Popup container
    CGFloat safeBottom = self.view.safeAreaInsets.bottom;
    CGFloat popupHeight = 180 + safeBottom;
    UIView *popup = [[UIView alloc] initWithFrame:CGRectMake(0,
                                                             self.view.bounds.size.height,
                                                             self.view.bounds.size.width,
                                                             popupHeight)];
    popup.backgroundColor = UIColor.whiteColor;
    popup.layer.cornerRadius = 16;
    popup.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    popup.clipsToBounds = YES;
    popup.tag = 1000;
    [self.view addSubview:popup];

    // Label — “You have selected”
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, popup.bounds.size.width - 40, 20)];
    label.text = @"You have selected:";
    label.textColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    [popup addSubview:label];

    // Mock location name
    UILabel *locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, popup.bounds.size.width - 40, 24)];
    locationLabel.text = @"Building A - 2nd Floor";
    self.selectedLocation = locationLabel.text;
    locationLabel.textColor = [UIColor blackColor];
    locationLabel.font = [UIFont boldSystemFontOfSize:17];
    [popup addSubview:locationLabel];

    // Buttons row
    CGFloat buttonWidth = (self.view.bounds.size.width - 48) / 2;
    CGFloat buttonY = popupHeight - 60 - safeBottom; // ✅ push up above safe area

    UIButton *reselectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    reselectButton.frame = CGRectMake(16, buttonY, buttonWidth, 44);
    [reselectButton setTitle:@"Reselect" forState:UIControlStateNormal];
    [reselectButton setTitleColor:[UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1]
                         forState:UIControlStateNormal];
    reselectButton.layer.borderWidth = 1.0;
    reselectButton.layer.borderColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1].CGColor;
    reselectButton.layer.cornerRadius = 8;
    [reselectButton addTarget:self action:@selector(dismissAddIssuePopup)
             forControlEvents:UIControlEventTouchUpInside];
    [popup addSubview:reselectButton];

    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeSystem];
    nextButton.frame = CGRectMake(32 + buttonWidth, buttonY, buttonWidth, 44);
    [nextButton setTitle:@"Next" forState:UIControlStateNormal];
    [nextButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    nextButton.backgroundColor = [UIColor colorWithRed:0/255.0 green:109/255.0 blue:141/255.0 alpha:1];
    nextButton.layer.cornerRadius = 8;
    [nextButton addTarget:self action:@selector(handleConfirmAddIssue)
         forControlEvents:UIControlEventTouchUpInside];
    [popup addSubview:nextButton];
  
    // Animate in
    [UIView animateWithDuration:0.3 animations:^{
        overlay.alpha = 1.0;
        popup.frame = CGRectMake(0,
                                 self.view.bounds.size.height - popupHeight,
                                 self.view.bounds.size.width,
                                 popupHeight);
    }];
}

- (void)dismissAddIssuePopup {
    NSLog(@"❌ Dismissing Add Issue popup");

    UIView *overlay = [self.view viewWithTag:999];
    UIView *popup = [self.view viewWithTag:1000];

    [UIView animateWithDuration:0.25 animations:^{
        overlay.alpha = 0.0;
        popup.frame = CGRectMake(0,
                                 self.view.bounds.size.height,
                                 popup.bounds.size.width,
                                 popup.bounds.size.height);
    } completion:^(BOOL finished) {
        [overlay removeFromSuperview];
        [popup removeFromSuperview];
    }];
}

- (void)handleConfirmAddIssue {
    NSLog(@"✅ Confirm Add Issue pressed");

    // Dismiss popup first
    [self dismissAddIssuePopup];

    // Then open AddIssueDetailsViewController after a short delay
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        AddIssueDetailsViewController *nextVC = [[AddIssueDetailsViewController alloc] init];
        nextVC.selectedLocationName = self.selectedLocation; // ✅ Pass it here
        nextVC.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:nextVC animated:YES completion:nil];
    });
}

#pragma mark - Actions

- (void)handleBack {
    [self dismissViewControllerAnimated:YES completion:nil];
}

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

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.planImageView;
}

#pragma mark - Status Bar Style
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent; // ✅ White text/icons
}

- (void)debugPrintAllIssues {
    for (NSDictionary *loc in self.locations) {
        NSString *roomName = loc[@"name"];
        NSArray *issues = loc[@"issue"];

        NSLog(@"📍 Room: %@ (%lu issues)", roomName, (unsigned long)issues.count);
        for (NSDictionary *issue in issues) {
            NSString *title = issue[@"issue"];
            NSString *status = issue[@"status_internal"];
            NSString *x = issue[@"pos_x"];
            NSString *y = issue[@"pos_y"];
            NSString *color = issue[@"status_in_color"];

            NSLog(@"   - %@ [%@] (x:%@, y:%@, color:%@)", title, status, x, y, color);
        }
    }
}

@end
