#import "FGMapViewController.h"
#import "FGStore.h"
#import "FGSpoofer.h"
#import "FGGoogleMaps.h"
#import "FGTheme.h"
#import "FGToast.h"
#import "FGRouteViewController.h"
#import "FGRouteSimulator.h"
#import "FGCoordTransform.h"

@interface FGMapViewController () <FGRouteViewControllerDelegate>
@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UITableView *suggestionsTable;
@property (nonatomic, strong) NSLayoutConstraint *suggestionsHeight;

@property (nonatomic, strong) UIView *crosshairView;
@property (nonatomic, strong) UIView *coordinateChip;
@property (nonatomic, strong) UILabel *coordinateLabel;

@property (nonatomic, strong) UIView *bottomCard;
@property (nonatomic, strong) UILabel *addressLabel;
@property (nonatomic, strong) UILabel *detailLabel;
@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic, strong) UISwitch *enableSwitch;
@property (nonatomic, strong) UIButton *applyButton;
@property (nonatomic, strong) UIButton *saveButton;
@property (nonatomic, strong) UIButton *manualButton;
@property (nonatomic, strong) UIButton *routeButton;
@property (nonatomic, strong) UIButton *recenterButton;
@property (nonatomic, strong) UIButton *mapStyleButton;
@property (nonatomic, strong) UIButton *moreButton;

@property (nonatomic, strong) UIView *simulationBar;
@property (nonatomic, strong) UILabel *simulationLabel;
@property (nonatomic, strong) UIButton *simulationStopButton;
@property (nonatomic, strong) NSLayoutConstraint *simulationHeight;
@property (nonatomic, strong) MKPointAnnotation *simulationAnnotation;
@property (nonatomic, assign) CFTimeInterval lastSimulationFollow;
@property (nonatomic, assign) CFTimeInterval lastSimulationGeocode;

@property (nonatomic, copy) NSArray<NSDictionary *> *suggestions;
@property (nonatomic, copy) NSString *currentAddress;
@property (nonatomic, assign) CLLocationCoordinate2D pickedCoordinate;
@property (nonatomic, assign) CLLocationCoordinate2D lastGeocodedCoordinate;
@property (nonatomic, strong) CLGeocoder *fallbackGeocoder;
@property (nonatomic, assign) BOOL showsHintOnce;
@end

@implementation FGMapViewController

#pragma mark - Vòng đời

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"Bản đồ";
    self.view.backgroundColor = [FGTheme screenBackground];
    self.suggestions = @[];
    self.lastGeocodedCoordinate = FGCoordinateMake(999, 999);
    self.fallbackGeocoder = [[CLGeocoder alloc] init];
    self.showsHintOnce = YES;

    if ([FGStore hasCoordinate]) {
        self.pickedCoordinate = [FGStore coordinate];
    } else {
        self.pickedCoordinate = FGCoordinateMake(21.028511, 105.854167); // Hồ Gươm, Hà Nội
    }

    [self setupMapView];
    [self setupSearchBar];
    [self setupSuggestionsTable];
    [self setupCrosshair];
    [self setupBottomCard];
    [self setupRecenterButton];
    [self setupConstraints];
    [self setupGestures];
    [self registerNotifications];

    [self centerMapOnCoordinate:self.pickedCoordinate animated:NO];
    [self refreshCard];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.showsHintOnce) {
        self.showsHintOnce = NO;
        [FGToast show:@"Kéo bản đồ để chọn vị trí. Tâm vòng tròn là điểm giả lập."
               inView:self.view];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark - Dựng giao diện

- (void)setupMapView {
    self.mapView = [[MKMapView alloc] initWithFrame:CGRectZero];
    self.mapView.translatesAutoresizingMaskIntoConstraints = NO;
    self.mapView.delegate = self;
    self.mapView.showsUserLocation = NO;
    self.mapView.showsCompass = NO;
    self.mapView.showsScale = YES;
    self.mapView.pointOfInterestFilter = [MKPointOfInterestFilter filterIncludingAllCategories];
    [self applyMapStyle];
    [self.view addSubview:self.mapView];
}

- (void)applyMapStyle {
    NSInteger style = [FGStore mapStyle];
    if (style == 1) {
        self.mapView.mapType = MKMapTypeSatellite;
    } else if (style == 2) {
        self.mapView.mapType = MKMapTypeHybrid;
    } else {
        self.mapView.mapType = MKMapTypeStandard;
    }
}

- (void)setupSearchBar {
    UIView *container = [[UIView alloc] initWithFrame:CGRectZero];
    container.translatesAutoresizingMaskIntoConstraints = NO;
    [FGTheme applyCardStyle:container];
    container.layer.shadowOpacity = 0.08;

    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
    self.searchBar.translatesAutoresizingMaskIntoConstraints = NO;
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"Tìm địa chỉ hoặc địa điểm…";
    self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    self.searchBar.backgroundImage = [[UIImage alloc] init];
    self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;

    [container addSubview:self.searchBar];
    [self.view addSubview:container];

    [NSLayoutConstraint activateConstraints:@[
        [container.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:10],
        [container.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [container.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        [container.heightAnchor constraintEqualToConstant:52],

        [self.searchBar.leadingAnchor constraintEqualToAnchor:container.leadingAnchor constant:2],
        [self.searchBar.trailingAnchor constraintEqualToAnchor:container.trailingAnchor constant:-2],
        [self.searchBar.centerYAnchor constraintEqualToAnchor:container.centerYAnchor]
    ]];
}

- (void)setupSuggestionsTable {
    self.suggestionsTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.suggestionsTable.translatesAutoresizingMaskIntoConstraints = NO;
    self.suggestionsTable.dataSource = self;
    self.suggestionsTable.delegate = self;
    self.suggestionsTable.rowHeight = 54;
    self.suggestionsTable.backgroundColor = [FGTheme cardBackground];
    self.suggestionsTable.layer.cornerRadius = 14;
    self.suggestionsTable.layer.cornerCurve = kCACornerCurveContinuous;
    self.suggestionsTable.layer.masksToBounds = YES;
    self.suggestionsTable.separatorInset = UIEdgeInsetsMake(0, 14, 0, 14);
    self.suggestionsTable.hidden = YES;
    [self.view addSubview:self.suggestionsTable];

    self.suggestionsHeight = [self.suggestionsTable.heightAnchor constraintEqualToConstant:0];
    [NSLayoutConstraint activateConstraints:@[
        [self.suggestionsTable.topAnchor constraintEqualToAnchor:self.searchBar.superview.bottomAnchor constant:8],
        [self.suggestionsTable.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.suggestionsTable.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        self.suggestionsHeight
    ]];
}

- (void)setupCrosshair {
    self.crosshairView = [[UIView alloc] initWithFrame:CGRectZero];
    self.crosshairView.translatesAutoresizingMaskIntoConstraints = NO;
    self.crosshairView.userInteractionEnabled = NO;

    CAShapeLayer *ring = [CAShapeLayer layer];
    ring.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 56, 56)].CGPath;
    ring.fillColor = [UIColor.whiteColor colorWithAlphaComponent:0.10].CGColor;
    ring.strokeColor = [FGTheme accent].CGColor;
    ring.lineWidth = 2.0;
    ring.shadowColor = UIColor.blackColor.CGColor;
    ring.shadowOpacity = 0.25;
    ring.shadowRadius = 4;
    ring.shadowOffset = CGSizeMake(0, 2);
    [self.crosshairView.layer addSublayer:ring];

    UIView *dot = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    dot.backgroundColor = [FGTheme accent];
    dot.layer.cornerRadius = 5;
    dot.translatesAutoresizingMaskIntoConstraints = NO;
    [self.crosshairView addSubview:dot];

    [NSLayoutConstraint activateConstraints:@[
        [dot.centerXAnchor constraintEqualToAnchor:self.crosshairView.centerXAnchor],
        [dot.centerYAnchor constraintEqualToAnchor:self.crosshairView.centerYAnchor],
        [dot.widthAnchor constraintEqualToConstant:10],
        [dot.heightAnchor constraintEqualToConstant:10]
    ]];

    self.coordinateChip = [[UIView alloc] initWithFrame:CGRectZero];
    self.coordinateChip.translatesAutoresizingMaskIntoConstraints = NO;
    self.coordinateChip.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.72];
    self.coordinateChip.layer.cornerRadius = 11;
    self.coordinateChip.layer.cornerCurve = kCACornerCurveContinuous;

    self.coordinateLabel = [FGTheme labelWithText:@"—" font:[FGTheme monoFontOfSize:12] color:UIColor.whiteColor];
    self.coordinateLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.coordinateLabel.textAlignment = NSTextAlignmentCenter;

    [self.coordinateChip addSubview:self.coordinateLabel];
    [self.view addSubview:self.coordinateChip];
    [self.view addSubview:self.crosshairView];

    [NSLayoutConstraint activateConstraints:@[
        [self.crosshairView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        [self.crosshairView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor],
        [self.crosshairView.widthAnchor constraintEqualToConstant:56],
        [self.crosshairView.heightAnchor constraintEqualToConstant:56],

        [self.coordinateChip.topAnchor constraintEqualToAnchor:self.crosshairView.bottomAnchor constant:8],
        [self.coordinateChip.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        [self.coordinateChip.heightAnchor constraintEqualToConstant:28],
        [self.coordinateChip.widthAnchor constraintGreaterThanOrEqualToConstant:150],

        [self.coordinateLabel.leadingAnchor constraintEqualToAnchor:self.coordinateChip.leadingAnchor constant:12],
        [self.coordinateLabel.trailingAnchor constraintEqualToAnchor:self.coordinateChip.trailingAnchor constant:-12],
        [self.coordinateLabel.centerYAnchor constraintEqualToAnchor:self.coordinateChip.centerYAnchor]
    ]];
}

- (void)setupBottomCard {
    self.bottomCard = [[UIView alloc] initWithFrame:CGRectZero];
    self.bottomCard.translatesAutoresizingMaskIntoConstraints = NO;
    [FGTheme applyCardStyle:self.bottomCard];

    self.addressLabel = [FGTheme labelWithText:@"Đang xác định địa chỉ…"
                                          font:[FGTheme bodyBoldFont]
                                         color:[FGTheme primaryText]];
    self.addressLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.addressLabel.numberOfLines = 2;

    self.detailLabel = [FGTheme labelWithText:@"" font:[FGTheme captionFont] color:[FGTheme secondaryText]];
    self.detailLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.detailLabel.numberOfLines = 2;

    self.moreButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.moreButton setImage:[FGTheme symbolNamed:@"ellipsis.circle.fill" size:22 weight:UIFontWeightRegular]
                     forState:UIControlStateNormal];
    self.moreButton.tintColor = [FGTheme secondaryText];
    self.moreButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.moreButton addTarget:self action:@selector(moreTapped) forControlEvents:UIControlEventTouchUpInside];

    self.statusLabel = [FGTheme labelWithText:@"Giả lập vị trí" font:[FGTheme bodyBoldFont] color:[FGTheme primaryText]];
    self.statusLabel.translatesAutoresizingMaskIntoConstraints = NO;

    self.enableSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
    self.enableSwitch.translatesAutoresizingMaskIntoConstraints = NO;
    self.enableSwitch.onTintColor = [FGTheme accent];
    [self.enableSwitch addTarget:self action:@selector(enableSwitchChanged:) forControlEvents:UIControlEventValueChanged];

    self.simulationBar = [[UIView alloc] initWithFrame:CGRectZero];
    self.simulationBar.translatesAutoresizingMaskIntoConstraints = NO;
    self.simulationBar.backgroundColor = [[FGTheme accent] colorWithAlphaComponent:0.10];
    self.simulationBar.layer.cornerRadius = 10;
    self.simulationBar.layer.cornerCurve = kCACornerCurveContinuous;
    self.simulationBar.clipsToBounds = YES;
    self.simulationBar.hidden = YES;

    self.simulationLabel = [FGTheme labelWithText:@"Đang mô phỏng…"
                                             font:[FGTheme captionFont]
                                            color:[FGTheme accent]];
    self.simulationLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.simulationLabel.numberOfLines = 1;
    self.simulationLabel.adjustsFontSizeToFitWidth = YES;
    self.simulationLabel.minimumScaleFactor = 0.8;

    self.simulationStopButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.simulationStopButton setImage:[FGTheme symbolNamed:@"stop.fill" size:16 weight:UIFontWeightBold]
                               forState:UIControlStateNormal];
    self.simulationStopButton.tintColor = [FGTheme danger];
    self.simulationStopButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.simulationStopButton addTarget:self
                                  action:@selector(stopSimulationTapped)
                        forControlEvents:UIControlEventTouchUpInside];

    [self.simulationBar addSubview:self.simulationLabel];
    [self.simulationBar addSubview:self.simulationStopButton];

    self.applyButton = [FGTheme filledButtonWithTitle:@"Đặt vị trí này"
                                                target:self
                                                action:@selector(applyButtonTapped)];
    self.applyButton.translatesAutoresizingMaskIntoConstraints = NO;

    self.saveButton = [FGTheme tintedButtonWithTitle:@"Lưu"
                                              target:self
                                              action:@selector(saveButtonTapped)];
    self.saveButton.translatesAutoresizingMaskIntoConstraints = NO;

    self.manualButton = [FGTheme tintedButtonWithTitle:@"Nhập tay"
                                                target:self
                                                action:@selector(manualButtonTapped)];
    self.manualButton.translatesAutoresizingMaskIntoConstraints = NO;

    self.routeButton = [FGTheme tintedButtonWithTitle:@"Mô phỏng"
                                               target:self
                                               action:@selector(routeButtonTapped)];
    self.routeButton.translatesAutoresizingMaskIntoConstraints = NO;

    [self.bottomCard addSubview:self.addressLabel];
    [self.bottomCard addSubview:self.detailLabel];
    [self.bottomCard addSubview:self.moreButton];
    [self.bottomCard addSubview:self.statusLabel];
    [self.bottomCard addSubview:self.enableSwitch];
    [self.bottomCard addSubview:self.simulationBar];
    [self.bottomCard addSubview:self.manualButton];
    [self.bottomCard addSubview:self.routeButton];
    [self.bottomCard addSubview:self.saveButton];
    [self.bottomCard addSubview:self.applyButton];
    [self.view addSubview:self.bottomCard];

    [NSLayoutConstraint activateConstraints:@[
        [self.moreButton.topAnchor constraintEqualToAnchor:self.bottomCard.topAnchor constant:8],
        [self.moreButton.trailingAnchor constraintEqualToAnchor:self.bottomCard.trailingAnchor constant:-10],
        [self.moreButton.widthAnchor constraintEqualToConstant:36],
        [self.moreButton.heightAnchor constraintEqualToConstant:36],

        [self.addressLabel.topAnchor constraintEqualToAnchor:self.bottomCard.topAnchor constant:14],
        [self.addressLabel.leadingAnchor constraintEqualToAnchor:self.bottomCard.leadingAnchor constant:16],
        [self.addressLabel.trailingAnchor constraintEqualToAnchor:self.moreButton.leadingAnchor constant:-6],

        [self.detailLabel.topAnchor constraintEqualToAnchor:self.addressLabel.bottomAnchor constant:3],
        [self.detailLabel.leadingAnchor constraintEqualToAnchor:self.addressLabel.leadingAnchor],
        [self.detailLabel.trailingAnchor constraintEqualToAnchor:self.addressLabel.trailingAnchor],

        [self.statusLabel.topAnchor constraintEqualToAnchor:self.detailLabel.bottomAnchor constant:12],
        [self.statusLabel.leadingAnchor constraintEqualToAnchor:self.addressLabel.leadingAnchor],
        [self.statusLabel.trailingAnchor constraintLessThanOrEqualToAnchor:self.enableSwitch.leadingAnchor constant:-8],

        [self.enableSwitch.centerYAnchor constraintEqualToAnchor:self.statusLabel.centerYAnchor],
        [self.enableSwitch.trailingAnchor constraintEqualToAnchor:self.addressLabel.trailingAnchor],

        [self.simulationBar.topAnchor constraintEqualToAnchor:self.statusLabel.bottomAnchor constant:10],
        [self.simulationBar.leadingAnchor constraintEqualToAnchor:self.addressLabel.leadingAnchor],
        [self.simulationBar.trailingAnchor constraintEqualToAnchor:self.enableSwitch.trailingAnchor],

        [self.simulationLabel.leadingAnchor constraintEqualToAnchor:self.simulationBar.leadingAnchor constant:12],
        [self.simulationLabel.centerYAnchor constraintEqualToAnchor:self.simulationBar.centerYAnchor],
        [self.simulationLabel.trailingAnchor constraintEqualToAnchor:self.simulationStopButton.leadingAnchor constant:-8],

        [self.simulationStopButton.trailingAnchor constraintEqualToAnchor:self.simulationBar.trailingAnchor constant:-10],
        [self.simulationStopButton.centerYAnchor constraintEqualToAnchor:self.simulationBar.centerYAnchor],
        [self.simulationStopButton.widthAnchor constraintEqualToConstant:28],
        [self.simulationStopButton.heightAnchor constraintEqualToConstant:28],

        [self.manualButton.topAnchor constraintEqualToAnchor:self.simulationBar.bottomAnchor constant:12],
        [self.manualButton.leadingAnchor constraintEqualToAnchor:self.addressLabel.leadingAnchor],
        [self.manualButton.heightAnchor constraintEqualToConstant:44],

        [self.routeButton.topAnchor constraintEqualToAnchor:self.manualButton.topAnchor],
        [self.routeButton.leadingAnchor constraintEqualToAnchor:self.manualButton.trailingAnchor constant:8],
        [self.routeButton.heightAnchor constraintEqualToConstant:44],
        [self.routeButton.widthAnchor constraintEqualToAnchor:self.manualButton.widthAnchor],

        [self.saveButton.topAnchor constraintEqualToAnchor:self.manualButton.topAnchor],
        [self.saveButton.leadingAnchor constraintEqualToAnchor:self.routeButton.trailingAnchor constant:8],
        [self.saveButton.trailingAnchor constraintEqualToAnchor:self.addressLabel.trailingAnchor],
        [self.saveButton.heightAnchor constraintEqualToConstant:44],
        [self.saveButton.widthAnchor constraintEqualToAnchor:self.manualButton.widthAnchor],

        [self.applyButton.topAnchor constraintEqualToAnchor:self.manualButton.bottomAnchor constant:8],
        [self.applyButton.leadingAnchor constraintEqualToAnchor:self.addressLabel.leadingAnchor],
        [self.applyButton.trailingAnchor constraintEqualToAnchor:self.addressLabel.trailingAnchor],
        [self.applyButton.heightAnchor constraintEqualToConstant:48],

        [self.bottomCard.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.bottomCard.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
        [self.bottomCard.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant:-10],
        [self.bottomCard.bottomAnchor constraintEqualToAnchor:self.applyButton.bottomAnchor constant:14]
    ]];

    self.simulationHeight = [self.simulationBar.heightAnchor constraintEqualToConstant:0];
    self.simulationHeight.active = YES;
}

- (void)setupRecenterButton {
    self.recenterButton = [FGTheme iconButtonNamed:@"location.fill" size:46 target:self action:@selector(recenterTapped)];
    self.recenterButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.recenterButton];

    self.mapStyleButton = [FGTheme iconButtonNamed:@"map" size:46 target:self action:@selector(mapStyleTapped)];
    self.mapStyleButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.mapStyleButton];

    [NSLayoutConstraint activateConstraints:@[
        [self.recenterButton.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-18],
        [self.recenterButton.bottomAnchor constraintEqualToAnchor:self.bottomCard.topAnchor constant:-12],
        [self.recenterButton.widthAnchor constraintEqualToConstant:46],
        [self.recenterButton.heightAnchor constraintEqualToConstant:46],

        [self.mapStyleButton.trailingAnchor constraintEqualToAnchor:self.recenterButton.trailingAnchor],
        [self.mapStyleButton.bottomAnchor constraintEqualToAnchor:self.recenterButton.topAnchor constant:-10],
        [self.mapStyleButton.widthAnchor constraintEqualToConstant:46],
        [self.mapStyleButton.heightAnchor constraintEqualToConstant:46]
    ]];
}

- (void)setupConstraints {
    [NSLayoutConstraint activateConstraints:@[
        [self.mapView.topAnchor constraintEqualToAnchor:self.view.topAnchor],
        [self.mapView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.mapView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.mapView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor]
    ]];
}

- (void)setupGestures {
    UILongPressGestureRecognizer *longPress =
        [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    longPress.minimumPressDuration = 0.45;
    [self.mapView addGestureRecognizer:longPress];
}

#pragma mark - Trạng thái

- (void)registerNotifications {
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(storeChanged:)
                   name:FGStoreDidChangeNotification object:nil];
    [center addObserver:self selector:@selector(spoofStateChanged:)
                   name:FGSpoofStateDidChangeNotification object:nil];
    [center addObserver:self selector:@selector(applyRequested:)
                   name:FGRequestApplyLocationNotification object:nil];
    [center addObserver:self selector:@selector(simulationChanged:)
                   name:FGRouteSimulationDidChangeNotification object:nil];
}

- (void)storeChanged:(NSNotification *)note {
    [self applyMapStyle];
    [self refreshCard];
}

- (void)spoofStateChanged:(NSNotification *)note {
    self.enableSwitch.on = [FGStore isEnabled];
    [self refreshCard];
}

- (void)applyRequested:(NSNotification *)note {
    NSDictionary *item = note.userInfo[@"item"];
    if (![item isKindOfClass:[NSDictionary class]]) return;

    CLLocationCoordinate2D coordinate = FGCoordinateMake([item[FGItemLatitude] doubleValue],
                                                         [item[FGItemLongitude] doubleValue]);
    if (!FGCoordinateValid(coordinate)) return;

    self.currentAddress = item[FGItemAddress];
    if (!self.currentAddress.length) self.currentAddress = item[FGItemName];

    [self centerMapOnCoordinate:coordinate animated:YES];
    self.pickedCoordinate = coordinate;
    self.lastGeocodedCoordinate = FGCoordinateMake(999, 999);
    [self refreshCard];
}

- (void)refreshCard {
    self.enableSwitch.on = [FGStore isEnabled];
    if ([FGStore isEnabled]) {
        self.statusLabel.textColor = [FGTheme accent];
        self.statusLabel.text = @"Đang giả lập";
    } else {
        self.statusLabel.textColor = [FGTheme primaryText];
        self.statusLabel.text = @"Giả lập vị trí";
    }

    if (self.currentAddress.length) {
        self.addressLabel.text = self.currentAddress;
    } else {
        self.addressLabel.text = @"Đang xác định địa chỉ…";
    }

    double altitude = [FGStore altitude];
    NSString *altitudeText = [FGStore isAltitudeEnabled]
        ? [NSString stringWithFormat:@"Độ cao %.0f m", altitude]
        : @"Độ cao: theo thiết bị";
    NSString *modeText = [FGStore coordMode] == 1 ? @"GCJ-02" : @"WGS84";
    self.detailLabel.text = [NSString stringWithFormat:@"%@  •  %@  •  %@",
                             FGCoordDetailedString(self.pickedCoordinate), altitudeText, modeText];
    self.coordinateLabel.text = FGCoordString(self.pickedCoordinate);
}

- (void)enableSwitchChanged:(UISwitch *)sender {
    if (sender.isOn) {
        [[FGSpoofer shared] applyCoordinate:self.pickedCoordinate];
        [self recordHistoryWithName:[self suggestedName]];
        UIImpactFeedbackGenerator *haptic = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
        [haptic impactOccurred];
        [FGToast show:@"Đã bật giả lập vị trí" inView:self.view];
    } else {
        [[FGSpoofer shared] setSpoofingEnabled:NO];
        [FGToast show:@"Đã tắt giả lập vị trí" inView:self.view];
    }
    [self refreshCard];
}

#pragma mark - Công cụ (lấy cảm hứng từ WrapPin)

- (void)mapStyleTapped {
    NSInteger style = ([FGStore mapStyle] + 1) % 3;
    [FGStore setMapStyle:style];
    [self applyMapStyle];

    NSArray<NSString *> *names = @[@"Bản đồ tiêu chuẩn", @"Bản đồ vệ tinh", @"Bản đồ vệ tinh lai"];
    [FGToast show:names[[FGStore mapStyle]] inView:self.view];
}

- (void)moreTapped {
    CLLocationCoordinate2D applied = FGCoordApplyMode(self.pickedCoordinate, (FGCoordMode)[FGStore coordMode]);
    NSString *modeName = [FGStore coordMode] == 1 ? @"GCJ-02" : @"WGS84";

    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:nil
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];

    __weak typeof(self) weakSelf = self;
    [sheet addAction:[UIAlertAction actionWithTitle:[NSString stringWithFormat:@"Sao chép toạ độ (%@)", modeName]
                                             style:UIAlertActionStyleDefault
                                           handler:^(UIAlertAction *action) {
        __strong typeof(weakSelf) self = weakSelf;
        [UIPasteboard generalPasteboard].string = FGCoordString(applied);
        [FGToast show:@"Đã sao chép toạ độ" inView:self.view];
    }]];

    [sheet addAction:[UIAlertAction actionWithTitle:@"Sao chép địa chỉ"
                                             style:UIAlertActionStyleDefault
                                           handler:^(UIAlertAction *action) {
        __strong typeof(weakSelf) self = weakSelf;
        NSString *address = self.currentAddress.length ? self.currentAddress : FGCoordString(self.pickedCoordinate);
        [UIPasteboard generalPasteboard].string = address;
        [FGToast show:@"Đã sao chép địa chỉ" inView:self.view];
    }]];

    [sheet addAction:[UIAlertAction actionWithTitle:@"Mở trong Apple Maps"
                                             style:UIAlertActionStyleDefault
                                           handler:^(UIAlertAction *action) {
        [weakSelf openMapsWithScheme:@"http://maps.apple.com/?ll=%@&q=%@"];
    }]];

    [sheet addAction:[UIAlertAction actionWithTitle:@"Mở trong Google Maps"
                                             style:UIAlertActionStyleDefault
                                           handler:^(UIAlertAction *action) {
        [weakSelf openMapsWithScheme:@"https://www.google.com/maps/search/?api=1&query=%@"];
    }]];

    [sheet addAction:[UIAlertAction actionWithTitle:@"Huỷ" style:UIAlertActionStyleCancel handler:nil]];
    sheet.popoverPresentationController.sourceView = self.moreButton;
    sheet.popoverPresentationController.sourceRect = self.moreButton.bounds;
    [self presentViewController:sheet animated:YES completion:nil];
}

- (void)openMapsWithScheme:(NSString *)format {
    NSString *coordinates = [NSString stringWithFormat:@"%.6f,%.6f",
                             self.pickedCoordinate.latitude, self.pickedCoordinate.longitude];
    NSString *encoded = [coordinates stringByAddingPercentEncodingWithAllowedCharacters:
                         [NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *urlString = [NSString stringWithFormat:format, encoded];
    NSURL *url = [NSURL URLWithString:urlString];
    if (!url) return;

    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
}

- (void)routeButtonTapped {
    if (!FGCoordinateValid(self.pickedCoordinate)) {
        [FGToast show:@"Chọn vị trí trên bản đồ trước." inView:self.view];
        return;
    }

    FGRouteViewController *controller =
        [[FGRouteViewController alloc] initWithStartCoordinate:self.pickedCoordinate
                                                    startTitle:self.currentAddress ?: FGCoordString(self.pickedCoordinate)];
    controller.delegate = self;
    controller.modalPresentationStyle = UIModalPresentationPageSheet;
    if (@available(iOS 15.0, *)) {
        controller.sheetPresentationController.prefersGrabberVisible = YES;
    }
    [self presentViewController:controller animated:YES completion:nil];
}

- (void)routeViewControllerDidRequestClose:(FGRouteViewController *)controller {
    [controller dismissViewControllerAnimated:YES completion:nil];
}

- (void)stopSimulationTapped {
    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"Dừng mô phỏng?"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Dừng, giữ vị trí cuối" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [[FGRouteSimulator shared] stop];
        [FGToast show:@"Đã dừng mô phỏng" inView:self.view];
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Dừng & trả vị trí thật" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        [[FGRouteSimulator shared] stopAndRestoreRealLocation];
        [FGToast show:@"Đã trả vị trí thật cho thiết bị" inView:self.view];
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Huỷ" style:UIAlertActionStyleCancel handler:nil]];
    sheet.popoverPresentationController.sourceView = self.simulationStopButton;
    sheet.popoverPresentationController.sourceRect = self.simulationStopButton.bounds;
    [self presentViewController:sheet animated:YES completion:nil];
}

- (void)simulationChanged:(NSNotification *)note {
    FGRouteSimulator *simulator = [FGRouteSimulator shared];
    BOOL running = simulator.isRunning;

    self.simulationBar.hidden = !running;
    self.simulationHeight.constant = running ? 36.0 : 0.0;

    if (!running) {
        [self refreshCard];
        return;
    }

    NSString *state = simulator.isPaused ? @"Tạm dừng" : @"Đang mô phỏng";
    self.simulationLabel.text = [NSString stringWithFormat:@"%@ • còn %@ • %.0f km/h",
                                 state,
                                 [self distanceText:simulator.remainingDistance],
                                 simulator.speedKPH];

    CLLocationCoordinate2D coordinate = simulator.currentCoordinate;
    if (FGCoordinateValid(coordinate)) {
        self.pickedCoordinate = coordinate;

        if (!self.simulationAnnotation) {
            self.simulationAnnotation = [[MKPointAnnotation alloc] init];
            self.simulationAnnotation.title = @"Đang mô phỏng";
            [self.mapView addAnnotation:self.simulationAnnotation];
        }
        self.simulationAnnotation.coordinate = coordinate;

        CFTimeInterval now = CACurrentMediaTime();
        if (!simulator.isPaused && now - self.lastSimulationFollow > 0.9) {
            self.lastSimulationFollow = now;
            [self.mapView setCenterCoordinate:coordinate animated:YES];
        }

        // Dịch ngược địa chỉ mỗi 5 giây để không spam API.
        if (now - self.lastSimulationGeocode > 5.0) {
            self.lastSimulationGeocode = now;
            self.lastGeocodedCoordinate = FGCoordinateMake(999, 999);
            [self resolveAddress];
        }
    }

    [self refreshCard];
}

- (NSString *)distanceText:(CLLocationDistance)meters {
    if (meters < 1000.0) {
        return [NSString stringWithFormat:@"%.0f m", meters];
    }
    NSString *km = [NSString stringWithFormat:@"%.1f", meters / 1000.0];
    km = [km stringByReplacingOccurrencesOfString:@"." withString:@","];
    return [km stringByAppendingString:@" km"];
}

#pragma mark - Hành động

- (void)applyButtonTapped {
    if (!FGCoordinateValid(self.pickedCoordinate)) {
        [FGToast show:@"Toạ độ không hợp lệ." inView:self.view];
        return;
    }

    if ([FGRouteSimulator shared].isRunning) {
        [[FGRouteSimulator shared] stop];
    }

    [[FGSpoofer shared] applyCoordinate:self.pickedCoordinate];
    [self recordHistoryWithName:[self suggestedName]];
    UINotificationFeedbackGenerator *haptic = [[UINotificationFeedbackGenerator alloc] init];
    [haptic notificationOccurred:UINotificationFeedbackTypeSuccess];
    [FGToast show:@"Đã đặt vị trí giả lập. Mở ứng dụng để kiểm tra." inView:self.view];
    [self refreshCard];
}

- (void)saveButtonTapped {
    NSString *defaultName = [self suggestedName];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Lưu địa điểm"
                                                                   message:@"Đặt tên để tìm lại nhanh hơn."
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.text = defaultName;
        textField.placeholder = @"Tên địa điểm";
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"Huỷ" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"Lưu" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSString *name = alert.textFields.firstObject.text;
        if (!name.length) name = defaultName;

        NSDictionary *item = @{
            FGItemName: name,
            FGItemAddress: self.currentAddress ?: @"",
            FGItemLatitude: @(self.pickedCoordinate.latitude),
            FGItemLongitude: @(self.pickedCoordinate.longitude),
            FGItemAltitude: @([FGStore altitude]),
            FGItemDate: [NSDate date]
        };
        [FGStore addSavedLocation:item];
        [FGToast show:@"Đã lưu địa điểm" inView:self.view];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)manualButtonTapped {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Nhập toạ độ"
                                                                   message:@"Ví dụ: 21.0278 và 105.8342"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"Vĩ độ (lat)";
        textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"Kinh độ (lng)";
        textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"Huỷ" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"Áp dụng" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSString *latText = alert.textFields.firstObject.text;
        NSString *lngText = alert.textFields.lastObject.text;

        double lat = 0, lng = 0;
        if (![self parseNumber:latText value:&lat] || ![self parseNumber:lngText value:&lng]) {
            [FGToast show:@"Toạ độ không hợp lệ." inView:self.view];
            return;
        }
        CLLocationCoordinate2D coordinate = FGCoordinateMake(lat, lng);
        if (!FGCoordinateValid(coordinate)) {
            [FGToast show:@"Toạ độ nằm ngoài phạm vi cho phép." inView:self.view];
            return;
        }

        self.lastGeocodedCoordinate = FGCoordinateMake(999, 999);
        self.currentAddress = nil;
        self.pickedCoordinate = coordinate;
        [self centerMapOnCoordinate:coordinate animated:YES];
        [self refreshCard];
        [self scheduleReverseGeocode];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)recenterTapped {
    if (![FGStore hasCoordinate]) {
        [FGToast show:@"Chưa có vị trí giả lập nào được đặt." inView:self.view];
        return;
    }
    [self centerMapOnCoordinate:[FGStore coordinate] animated:YES];
    [self refreshCard];
}

- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture {
    if (gesture.state != UIGestureRecognizerStateBegan) return;

    CGPoint point = [gesture locationInView:self.mapView];
    CLLocationCoordinate2D coordinate = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
    if (!FGCoordinateValid(coordinate)) return;

    self.pickedCoordinate = coordinate;
    [self.mapView removeAnnotations:self.mapView.annotations];

    MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
    annotation.coordinate = coordinate;
    annotation.title = @"Vị trí đã chọn";
    [self.mapView addAnnotation:annotation];

    [self centerMapOnCoordinate:coordinate animated:YES];
    self.lastGeocodedCoordinate = FGCoordinateMake(999, 999);
    self.currentAddress = nil;
    [self refreshCard];
    [self scheduleReverseGeocode];
}

#pragma mark - Bản đồ

- (void)centerMapOnCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated {
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coordinate, 900, 900);
    [self.mapView setRegion:region animated:animated];
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    if ([FGRouteSimulator shared].isRunning) return;

    CGPoint center = CGPointMake(mapView.bounds.size.width / 2.0, mapView.bounds.size.height / 2.0);
    CLLocationCoordinate2D coordinate = [mapView convertPoint:center toCoordinateFromView:mapView];
    if (!FGCoordinateValid(coordinate)) return;

    self.pickedCoordinate = coordinate;
    [self refreshCard];
    [self scheduleReverseGeocode];
}

#pragma mark - Địa chỉ

- (void)scheduleReverseGeocode {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(resolveAddress) object:nil];
    [self performSelector:@selector(resolveAddress) withObject:nil afterDelay:0.6];
}

- (void)resolveAddress {
    CLLocationCoordinate2D coordinate = self.pickedCoordinate;
    if (!FGCoordinateValid(coordinate)) return;

    CLLocation *current = [[CLLocation alloc] initWithLatitude:coordinate.latitude
                                                    longitude:coordinate.longitude];
    CLLocation *last = [[CLLocation alloc] initWithLatitude:self.lastGeocodedCoordinate.latitude
                                                  longitude:self.lastGeocodedCoordinate.longitude];
    if (self.lastGeocodedCoordinate.latitude < 900 &&
        [current distanceFromLocation:last] < 15.0) {
        return;
    }
    self.lastGeocodedCoordinate = coordinate;

    __weak typeof(self) weakSelf = self;
    [FGGoogleMaps reverseGeocode:coordinate completion:^(NSString *address) {
        __strong typeof(weakSelf) self = weakSelf;
        if (!self) return;

        CLLocation *picked = [[CLLocation alloc] initWithLatitude:self.pickedCoordinate.latitude
                                                       longitude:self.pickedCoordinate.longitude];
        CLLocation *asked = [[CLLocation alloc] initWithLatitude:coordinate.latitude
                                                       longitude:coordinate.longitude];
        if ([picked distanceFromLocation:asked] > 200.0) return;

        self.currentAddress = address;
        self.addressLabel.text = address.length ? address : @"Không xác định được địa chỉ";
    }];
}

- (NSString *)suggestedName {
    NSString *address = self.currentAddress;
    if (!address.length) return @"Vị trí trên bản đồ";
    NSArray *parts = [address componentsSeparatedByString:@","];
    NSString *first = [parts.firstObject stringByTrimmingCharactersInSet:
                       [NSCharacterSet whitespaceCharacterSet]];
    return first.length ? first : @"Vị trí trên bản đồ";
}

- (void)recordHistoryWithName:(NSString *)name {
    NSDictionary *item = @{
        FGItemName: name ?: @"Vị trí trên bản đồ",
        FGItemAddress: self.currentAddress ?: @"",
        FGItemLatitude: @(self.pickedCoordinate.latitude),
        FGItemLongitude: @(self.pickedCoordinate.longitude),
        FGItemAltitude: @([FGStore altitude]),
        FGItemDate: [NSDate date]
    };
    [FGStore addHistoryItem:item];
}

#pragma mark - UISearchBarDelegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(performAutocomplete) object:nil];

    if (searchText.length < 2) {
        [self hideSuggestions];
        return;
    }
    if (![FGGoogleMaps isConfigured]) {
        [self hideSuggestions];
        return;
    }
    [self performSelector:@selector(performAutocomplete) withObject:nil afterDelay:0.35];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    NSString *query = searchBar.text;
    if (!query.length) return;

    if (self.suggestions.count) {
        [self selectSuggestionAtIndex:0];
        return;
    }

    __weak typeof(self) weakSelf = self;
    [FGGoogleMaps searchQuery:query completion:^(NSDictionary *place, NSString *errorMessage) {
        __strong typeof(weakSelf) self = weakSelf;
        if (!self) return;
        if (!place) {
            [FGToast show:errorMessage ?: @"Không tìm thấy địa điểm." inView:self.view];
            return;
        }
        [self moveToPlace:place];
    }];
}

- (void)performAutocomplete {
    NSString *query = self.searchBar.text;
    if (query.length < 2) return;

    __weak typeof(self) weakSelf = self;
    [FGGoogleMaps autocompleteQuery:query completion:^(NSArray<NSDictionary *> *suggestions, NSString *errorMessage) {
        __strong typeof(weakSelf) self = weakSelf;
        if (!self) return;
        if (![self.searchBar.text isEqualToString:query]) return;

        self.suggestions = suggestions ?: @[];
        [self.suggestionsTable reloadData];
        [self updateSuggestionsHeight];
    }];
}

- (void)selectSuggestionAtIndex:(NSInteger)index {
    if (index < 0 || index >= (NSInteger)self.suggestions.count) return;
    NSDictionary *suggestion = self.suggestions[index];
    NSString *placeID = suggestion[@"placeID"];
    self.searchBar.text = suggestion[@"title"];
    [self.searchBar resignFirstResponder];
    [self hideSuggestions];

    __weak typeof(self) weakSelf = self;
    [FGGoogleMaps lookupPlaceID:placeID completion:^(NSDictionary *place, NSString *errorMessage) {
        __strong typeof(weakSelf) self = weakSelf;
        if (!self) return;
        if (!place) {
            [FGToast show:errorMessage ?: @"Không lấy được thông tin địa điểm." inView:self.view];
            return;
        }
        [self moveToPlace:place];
    }];
}

- (void)moveToPlace:(NSDictionary *)place {
    double lat = [place[@"lat"] doubleValue];
    double lng = [place[@"lng"] doubleValue];
    CLLocationCoordinate2D coordinate = FGCoordinateMake(lat, lng);
    if (!FGCoordinateValid(coordinate)) {
        [FGToast show:@"Địa điểm không có toạ độ hợp lệ." inView:self.view];
        return;
    }

    self.currentAddress = place[@"address"] ?: place[@"name"];
    self.pickedCoordinate = coordinate;
    self.lastGeocodedCoordinate = coordinate;

    [self.mapView removeAnnotations:self.mapView.annotations];
    MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
    annotation.coordinate = coordinate;
    annotation.title = place[@"name"] ?: @"Địa điểm";
    [self.mapView addAnnotation:annotation];

    [self centerMapOnCoordinate:coordinate animated:YES];
    [self refreshCard];
}

- (void)hideSuggestions {
    self.suggestions = @[];
    [self.suggestionsTable reloadData];
    [self updateSuggestionsHeight];
}

- (void)updateSuggestionsHeight {
    NSInteger count = (NSInteger)self.suggestions.count;
    self.suggestionsTable.hidden = (count == 0);
    self.suggestionsHeight.constant = MIN(300, MAX(0, count * 54));
    [self.view layoutIfNeeded];
}

#pragma mark - UITableView

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"FGSuggestionCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    NSDictionary *suggestion = self.suggestions[indexPath.row];
    cell.textLabel.text = suggestion[@"title"];
    cell.textLabel.font = [FGTheme bodyBoldFont];
    cell.detailTextLabel.text = suggestion[@"subtitle"];
    cell.detailTextLabel.font = [FGTheme captionFont];
    cell.detailTextLabel.textColor = [FGTheme secondaryText];
    cell.backgroundColor = [FGTheme cardBackground];
    cell.textLabel.textColor = [FGTheme primaryText];
    cell.imageView.image = [FGTheme symbolNamed:@"mappin.circle" size:20 weight:UIFontWeightRegular];
    cell.imageView.tintColor = [FGTheme accent];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self selectSuggestionAtIndex:indexPath.row];
}

#pragma mark - Tiện ích

- (BOOL)parseNumber:(NSString *)text value:(double *)value {
    if (!text.length) return NO;
    NSString *normalized = [text stringByReplacingOccurrencesOfString:@"," withString:@"."];
    NSScanner *scanner = [NSScanner scannerWithString:normalized];
    double parsed = 0;
    if (![scanner scanDouble:&parsed]) return NO;
    if (!scanner.isAtEnd) return NO;
    if (isnan(parsed) || isinf(parsed)) return NO;
    *value = parsed;
    return YES;
}

@end
