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

@interface FGRouteViewController () <UITextFieldDelegate>

@property (nonatomic, assign) CLLocationCoordinate2D startCoordinate;
@property (nonatomic, copy) NSString *startTitle;

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIStackView *stack;

@property (nonatomic, strong) UILabel *startLabel;
@property (nonatomic, strong) UILabel *startDetailLabel;
@property (nonatomic, strong) UITextField *destinationField;
@property (nonatomic, strong) UIButton *searchButton;
@property (nonatomic, strong) UILabel *destinationLabel;

@property (nonatomic, strong) UISegmentedControl *transportControl;
@property (nonatomic, strong) UILabel *speedLabel;
@property (nonatomic, strong) UISlider *speedSlider;
@property (nonatomic, strong) UIStackView *presetStack;

@property (nonatomic, strong) UILabel *distanceLabel;
@property (nonatomic, strong) UILabel *etaLabel;
@property (nonatomic, strong) UILabel *statusLabel;

@property (nonatomic, strong) UIButton *startButton;
@property (nonatomic, strong) UIButton *pauseButton;
@property (nonatomic, strong) UIButton *stopButton;

@property (nonatomic, assign) CLLocationCoordinate2D destinationCoordinate;
@property (nonatomic, copy) NSString *destinationTitle;
@property (nonatomic, assign) BOOL planned;

@end

@implementation FGRouteViewController

- (instancetype)initWithStartCoordinate:(CLLocationCoordinate2D)coordinate
                            startTitle:(NSString *)title {
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        _startCoordinate = coordinate;
        _startTitle = [title copy];
        _destinationCoordinate = FGCoordinateMake(0, 0);
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [FGTheme screenBackground];

    [self setupHeader];
    [self setupContent];
    [self setupActions];
    [self applyTransportUI];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(simulationChanged:)
                                                 name:FGRouteSimulationDidChangeNotification
                                               object:nil];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                         action:@selector(dismissKeyboard)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];

    [self refreshFromSimulator];
}

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

#pragma mark - Dựng giao diện

- (void)setupHeader {
    UILabel *title = [FGTheme labelWithText:@"Mô phỏng tuyến" font:[FGTheme titleFont] color:[FGTheme primaryText]];
    title.translatesAutoresizingMaskIntoConstraints = NO;

    UIButton *close = [UIButton buttonWithType:UIButtonTypeSystem];
    [close setImage:[FGTheme symbolNamed:@"xmark.circle.fill" size:24 weight:UIFontWeightRegular]
           forState:UIControlStateNormal];
    close.tintColor = [FGTheme secondaryText];
    close.translatesAutoresizingMaskIntoConstraints = NO;
    [close addTarget:self action:@selector(closeTapped) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:title];
    [self.view addSubview:close];

    [NSLayoutConstraint activateConstraints:@[
        [title.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:16],
        [title.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:20],

        [close.centerYAnchor constraintEqualToAnchor:title.centerYAnchor],
        [close.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-20],
        [close.widthAnchor constraintEqualToConstant:32],
        [close.heightAnchor constraintEqualToConstant:32]
    ]];
}

- (void)setupContent {
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    self.scrollView.alwaysBounceVertical = YES;
    self.scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

    self.stack = [[UIStackView alloc] initWithFrame:CGRectZero];
    self.stack.axis = UILayoutConstraintAxisVertical;
    self.stack.spacing = 14;
    self.stack.translatesAutoresizingMaskIntoConstraints = NO;

    [self.scrollView addSubview:self.stack];
    [self.view addSubview:self.scrollView];

    [NSLayoutConstraint activateConstraints:@[
        [self.scrollView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:56],
        [self.scrollView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [self.scrollView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],

        [self.stack.topAnchor constraintEqualToAnchor:self.scrollView.topAnchor constant:6],
        [self.stack.leadingAnchor constraintEqualToAnchor:self.scrollView.leadingAnchor constant:16],
        [self.stack.trailingAnchor constraintEqualToAnchor:self.scrollView.trailingAnchor constant:-16],
        [self.stack.bottomAnchor constraintEqualToAnchor:self.scrollView.bottomAnchor constant:-24],
        [self.stack.widthAnchor constraintEqualToAnchor:self.scrollView.widthAnchor constant:-32]
    ]];

    [self buildEndpointsCard];
    [self buildSpeedCard];
    [self buildSummaryCard];
}

- (UIView *)cardWithArrangedSubviews:(NSArray<UIView *> *)views {
    UIView *card = [[UIView alloc] initWithFrame:CGRectZero];
    [FGTheme applyCardStyle:card];
    card.translatesAutoresizingMaskIntoConstraints = NO;

    UIStackView *inner = [[UIStackView alloc] initWithArrangedSubviews:views];
    inner.axis = UILayoutConstraintAxisVertical;
    inner.spacing = 10;
    inner.translatesAutoresizingMaskIntoConstraints = NO;

    [card addSubview:inner];
    [NSLayoutConstraint activateConstraints:@[
        [inner.topAnchor constraintEqualToAnchor:card.topAnchor constant:14],
        [inner.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:14],
        [inner.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-14],
        [inner.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-14]
    ]];
    return card;
}

- (UILabel *)sectionTitle:(NSString *)text {
    return [FGTheme labelWithText:text.uppercaseString
                             font:[FGTheme sectionTitleFont]
                            color:[FGTheme secondaryText]];
}

- (void)buildEndpointsCard {
    UILabel *section = [self sectionTitle:@"Hành trình"];

    self.startLabel = [FGTheme labelWithText:self.startTitle.length ? self.startTitle : @"Điểm bắt đầu"
                                        font:[FGTheme bodyBoldFont]
                                       color:[FGTheme primaryText]];
    self.startDetailLabel = [FGTheme labelWithText:FGCoordString(self.startCoordinate)
                                              font:[FGTheme monoFontOfSize:12]
                                             color:[FGTheme secondaryText]];

    UIView *divider = [[UIView alloc] initWithFrame:CGRectZero];
    divider.backgroundColor = [FGTheme separator];
    divider.translatesAutoresizingMaskIntoConstraints = NO;
    [divider.heightAnchor constraintEqualToConstant:1].active = YES;

    self.destinationField = [[UITextField alloc] initWithFrame:CGRectZero];
    self.destinationField.placeholder = @"Tìm điểm đến (địa chỉ hoặc lat, lng)";
    self.destinationField.font = [FGTheme bodyFont];
    self.destinationField.textColor = [FGTheme primaryText];
    self.destinationField.backgroundColor = [FGTheme screenBackground];
    self.destinationField.layer.cornerRadius = 11;
    self.destinationField.layer.cornerCurve = kCACornerCurveContinuous;
    self.destinationField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 12, 1)];
    self.destinationField.leftViewMode = UITextFieldViewModeAlways;
    self.destinationField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.destinationField.returnKeyType = UIReturnKeySearch;
    self.destinationField.delegate = self;
    self.destinationField.translatesAutoresizingMaskIntoConstraints = NO;
    [self.destinationField.heightAnchor constraintEqualToConstant:44].active = YES;

    self.searchButton = [FGTheme tintedButtonWithTitle:@"Tìm"
                                                target:self
                                                action:@selector(searchDestination)];
    self.searchButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.searchButton.widthAnchor constraintEqualToConstant:66].active = YES;
    [self.searchButton.heightAnchor constraintEqualToConstant:44].active = YES;

    UIStackView *searchRow = [[UIStackView alloc] initWithArrangedSubviews:@[self.destinationField, self.searchButton]];
    searchRow.axis = UILayoutConstraintAxisHorizontal;
    searchRow.spacing = 8;

    self.destinationLabel = [FGTheme labelWithText:@"Chưa chọn điểm đến"
                                              font:[FGTheme captionFont]
                                             color:[FGTheme secondaryText]];

    UIView *card = [self cardWithArrangedSubviews:@[section, self.startLabel, self.startDetailLabel,
                                                    divider, searchRow, self.destinationLabel]];
    [self.stack addArrangedSubview:card];
}

- (void)buildSpeedCard {
    UILabel *section = [self sectionTitle:@"Phương tiện & tốc độ"];

    self.transportControl = [[UISegmentedControl alloc] initWithItems:@[@"Đi bộ", @"Lái xe"]];
    self.transportControl.selectedSegmentIndex = 0;
    [self.transportControl addTarget:self action:@selector(transportChanged)
                    forControlEvents:UIControlEventValueChanged];

    self.speedLabel = [FGTheme labelWithText:@"Tốc độ: 5 km/h"
                                        font:[FGTheme bodyBoldFont]
                                       color:[FGTheme primaryText]];

    self.speedSlider = [[UISlider alloc] initWithFrame:CGRectZero];
    self.speedSlider.minimumTrackTintColor = [FGTheme accent];
    self.speedSlider.maximumTrackTintColor = [FGTheme separator];
    [self.speedSlider addTarget:self action:@selector(speedChanged)
               forControlEvents:UIControlEventValueChanged];

    self.presetStack = [[UIStackView alloc] initWithFrame:CGRectZero];
    self.presetStack.axis = UILayoutConstraintAxisHorizontal;
    self.presetStack.spacing = 8;
    self.presetStack.distribution = UIStackViewDistributionFillEqually;
    [self.presetStack.heightAnchor constraintEqualToConstant:36].active = YES;

    UIView *card = [self cardWithArrangedSubviews:@[section, self.transportControl,
                                                    self.speedLabel, self.speedSlider, self.presetStack]];
    [self.stack addArrangedSubview:card];
}

- (void)buildSummaryCard {
    UILabel *section = [self sectionTitle:@"Tuyến đường"];

    self.distanceLabel = [FGTheme labelWithText:@"Chưa lập tuyến"
                                           font:[FGTheme bodyBoldFont]
                                          color:[FGTheme primaryText]];
    self.etaLabel = [FGTheme labelWithText:@"Chọn điểm đến rồi bấm “Bắt đầu”."
                                      font:[FGTheme captionFont]
                                     color:[FGTheme secondaryText]];
    self.statusLabel = [FGTheme labelWithText:@"" font:[FGTheme captionFont] color:[FGTheme accent]];
    self.statusLabel.hidden = YES;

    UIView *card = [self cardWithArrangedSubviews:@[section, self.distanceLabel,
                                                    self.etaLabel, self.statusLabel]];
    [self.stack addArrangedSubview:card];
}

- (void)setupActions {
    UIView *container = [[UIView alloc] initWithFrame:CGRectZero];
    container.backgroundColor = [FGTheme screenBackground];
    container.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:container];

    self.startButton = [FGTheme filledButtonWithTitle:@"Bắt đầu mô phỏng"
                                               target:self
                                               action:@selector(startTapped)];
    self.pauseButton = [FGTheme tintedButtonWithTitle:@"Tạm dừng"
                                               target:self
                                               action:@selector(pauseTapped)];
    self.stopButton = [FGTheme tintedButtonWithTitle:@"Dừng & trả vị trí thật"
                                              target:self
                                              action:@selector(stopTapped)];
    [self.stopButton setTitleColor:[FGTheme danger] forState:UIControlStateNormal];
    self.stopButton.backgroundColor = [[FGTheme danger] colorWithAlphaComponent:0.12];

    for (UIButton *button in @[self.startButton, self.pauseButton, self.stopButton]) {
        button.translatesAutoresizingMaskIntoConstraints = NO;
        [button.heightAnchor constraintEqualToConstant:48].active = YES;
        [container addSubview:button];
    }
    self.pauseButton.hidden = YES;
    self.stopButton.hidden = YES;

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

        [self.startButton.topAnchor constraintEqualToAnchor:container.topAnchor constant:10],
        [self.startButton.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
        [self.startButton.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],

        [self.pauseButton.topAnchor constraintEqualToAnchor:self.startButton.bottomAnchor constant:8],
        [self.pauseButton.leadingAnchor constraintEqualToAnchor:self.startButton.leadingAnchor],
        [self.pauseButton.widthAnchor constraintEqualToAnchor:self.stopButton.widthAnchor],

        [self.stopButton.topAnchor constraintEqualToAnchor:self.pauseButton.topAnchor],
        [self.stopButton.leadingAnchor constraintEqualToAnchor:self.pauseButton.trailingAnchor constant:8],
        [self.stopButton.trailingAnchor constraintEqualToAnchor:self.startButton.trailingAnchor],

        [container.bottomAnchor constraintEqualToAnchor:self.stopButton.bottomAnchor constant:10]
    ]];

    UIEdgeInsets inset = UIEdgeInsetsMake(0, 0, 112, 0);
    self.scrollView.contentInset = inset;
    self.scrollView.scrollIndicatorInsets = inset;
}

#pragma mark - Hành động

- (void)closeTapped {
    if (self.delegate) {
        [self.delegate routeViewControllerDidRequestClose:self];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)transportChanged {
    [self applyTransportUI];
    self.planned = NO;
    self.statusLabel.hidden = YES;
}

- (void)applyTransportUI {
    FGTransportType transport = [self selectedTransport];
    BOOL driving = (transport == FGTransportTypeDriving);

    self.speedSlider.minimumValue = driving ? 5.0 : 1.0;
    self.speedSlider.maximumValue = driving ? 240.0 : 12.0;
    self.speedSlider.value = driving ? [FGStore driveSpeed] : [FGStore walkSpeed];

    for (UIView *view in self.presetStack.arrangedSubviews) {
        [view removeFromSuperview];
    }
    NSArray<NSNumber *> *presets = driving ? @[@30, @50, @80] : @[@3, @5, @8];
    for (NSNumber *preset in presets) {
        UIButton *button = [FGTheme tintedButtonWithTitle:[NSString stringWithFormat:@"%@ km/h", preset]
                                                  target:self
                                                  action:@selector(presetTapped:)];
        button.titleLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightSemibold];
        button.tag = preset.integerValue;
        [self.presetStack addArrangedSubview:button];
    }

    [self speedChanged];
}

- (void)presetTapped:(UIButton *)sender {
    self.speedSlider.value = (float)sender.tag;
    [self speedChanged];
}

- (void)speedChanged {
    double kmh = round(self.speedSlider.value);
    FGTransportType transport = [self selectedTransport];
    if (transport == FGTransportTypeDriving) {
        [FGStore setDriveSpeed:kmh];
    } else {
        [FGStore setWalkSpeed:kmh];
    }
    self.speedLabel.text = [NSString stringWithFormat:@"Tốc độ: %.0f km/h", kmh];
    self.planned = NO;
    [self refreshEtaIfPossible];
}

- (FGTransportType)selectedTransport {
    return self.transportControl.selectedSegmentIndex == 1
        ? FGTransportTypeDriving : FGTransportTypeWalking;
}

- (void)searchDestination {
    [self dismissKeyboard];
    NSString *query = [self.destinationField.text stringByTrimmingCharactersInSet:
                       [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (!query.length) {
        [FGToast show:@"Nhập địa chỉ hoặc “lat, lng”." inView:self.view];
        return;
    }

    // Ưu tiên hiểu chuỗi dạng "21.02, 105.83".
    NSArray<NSString *> *parts = [query componentsSeparatedByString:@","];
    if (parts.count == 2) {
        double lat = 0, lng = 0;
        NSScanner *latScanner = [NSScanner scannerWithString:parts[0]];
        NSScanner *lngScanner = [NSScanner scannerWithString:parts[1]];
        if ([latScanner scanDouble:&lat] && [lngScanner scanDouble:&lng] &&
            FGCoordinateValid(FGCoordinateMake(lat, lng))) {
            self.destinationCoordinate = FGCoordinateMake(lat, lng);
            self.destinationTitle = query;
            self.destinationLabel.text = [NSString stringWithFormat:@"Điểm đến • %@", FGCoordString(self.destinationCoordinate)];
            self.planned = NO;
            [self updateDistancePlaceholder];
            return;
        }
    }

    self.searchButton.enabled = NO;
    __weak typeof(self) weakSelf = self;
    [FGGoogleMaps searchQuery:query completion:^(NSDictionary *place, NSString *errorMessage) {
        __strong typeof(weakSelf) self = weakSelf;
        if (!self) return;
        self.searchButton.enabled = YES;

        if (!place) {
            [FGToast show:errorMessage ?: @"Không tìm thấy điểm đến." inView:self.view];
            return;
        }

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

        self.destinationCoordinate = coordinate;
        self.destinationTitle = place[@"name"] ?: query;
        self.destinationField.text = self.destinationTitle;
        self.destinationLabel.text = place[@"address"] ?: FGCoordString(coordinate);
        self.planned = NO;
        [self updateDistancePlaceholder];
    }];
}

- (void)updateDistancePlaceholder {
    CLLocation *from = [[CLLocation alloc] initWithLatitude:self.startCoordinate.latitude
                                                  longitude:self.startCoordinate.longitude];
    CLLocation *to = [[CLLocation alloc] initWithLatitude:self.destinationCoordinate.latitude
                                                longitude:self.destinationCoordinate.longitude];
    CLLocationDistance meters = [from distanceFromLocation:to];
    self.distanceLabel.text = [NSString stringWithFormat:@"Đường chim bay: %@",
                               [self formatDistance:meters]];
    self.etaLabel.text = @"Bấm “Bắt đầu mô phỏng” để lập tuyến thật.";
}

- (void)startTapped {
    if (!FGCoordinateValid(self.destinationCoordinate)) {
        [FGToast show:@"Chọn điểm đến trước." inView:self.view];
        return;
    }

    UIImpactFeedbackGenerator *haptic = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];
    [haptic impactOccurred];

    self.startButton.enabled = NO;
    [self.startButton setTitle:@"Đang lập tuyến…" forState:UIControlStateNormal];

    FGRouteSimulator *simulator = [FGRouteSimulator shared];
    __weak typeof(self) weakSelf = self;
    [simulator planFrom:self.startCoordinate
                     to:self.destinationCoordinate
              transport:[self selectedTransport]
             completion:^(CLLocationDistance distance, NSTimeInterval duration, NSString *errorMessage) {
        __strong typeof(weakSelf) self = weakSelf;
        if (!self) return;

        self.startButton.enabled = YES;
        [self.startButton setTitle:@"Bắt đầu mô phỏng" forState:UIControlStateNormal];

        if (errorMessage) {
            [FGToast show:errorMessage inView:self.view];
            return;
        }

        simulator.destinationName = self.destinationTitle;
        self.planned = YES;
        [simulator start];
        [FGToast show:@"Đã bắt đầu mô phỏng tuyến" inView:self.view];
    }];
}

- (void)pauseTapped {
    FGRouteSimulator *simulator = [FGRouteSimulator shared];
    if (simulator.isPaused) {
        [simulator resume];
    } else {
        [simulator pause];
    }
    [self refreshFromSimulator];
}

- (void)stopTapped {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Dừng mô phỏng?"
                                                                   message:@"Bạn có muốn tắt giả lập và trả vị trí thật cho thiết bị?"
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"Tiếp tục chạy" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"Dừng, giữ vị trí cuối" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [[FGRouteSimulator shared] stop];
        [self refreshFromSimulator];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"Dừng & trả vị trí thật" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        [[FGRouteSimulator shared] stopAndRestoreRealLocation];
        [self refreshFromSimulator];
    }]];

    alert.popoverPresentationController.sourceView = self.stopButton;
    alert.popoverPresentationController.sourceRect = self.stopButton.bounds;
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - Cập nhật trạng thái

- (void)simulationChanged:(NSNotification *)note {
    [self refreshFromSimulator];
    if ([note.userInfo[@"finished"] boolValue]) {
        [FGToast show:@"Đã tới điểm đến." inView:self.view];
    }
}

- (void)refreshFromSimulator {
    FGRouteSimulator *simulator = [FGRouteSimulator shared];

    self.startButton.hidden = simulator.isRunning;
    self.pauseButton.hidden = !simulator.isRunning;
    self.stopButton.hidden = !simulator.isRunning;

    if (!simulator.isRunning) {
        self.pauseButton.hidden = YES;
        self.stopButton.hidden = YES;
        self.startButton.hidden = NO;
        self.statusLabel.hidden = YES;
        [self refreshEtaIfPossible];
        return;
    }

    [self.pauseButton setTitle:simulator.isPaused ? @"Tiếp tục" : @"Tạm dừng"
                      forState:UIControlStateNormal];

    double metersPerSecond = MAX(0.3, simulator.speedKPH / 3.6);
    double remainingSeconds = simulator.remainingDistance / metersPerSecond;

    self.statusLabel.hidden = NO;
    self.statusLabel.text = simulator.isPaused
        ? @"Đang tạm dừng"
        : @"Đang mô phỏng…";

    self.distanceLabel.text = [NSString stringWithFormat:@"Còn lại %@ / %@",
                               [self formatDistance:simulator.remainingDistance],
                               [self formatDistance:simulator.totalDistance]];
    self.etaLabel.text = [NSString stringWithFormat:@"Tốc độ %.0f km/h • còn khoảng %@",
                          simulator.speedKPH, [self formatDuration:remainingSeconds]];
}

- (void)refreshEtaIfPossible {
    if (!self.planned) return;
    FGRouteSimulator *simulator = [FGRouteSimulator shared];
    if (simulator.totalDistance <= 0) return;

    double metersPerSecond = MAX(0.3, self.speedSlider.value / 3.6);
    self.distanceLabel.text = [self formatDistance:simulator.totalDistance];
    self.etaLabel.text = [NSString stringWithFormat:@"Dự kiến %@ với tốc độ %.0f km/h",
                          [self formatDuration:simulator.totalDistance / metersPerSecond],
                          self.speedSlider.value];
}

#pragma mark - Định dạng

- (NSString *)formatDistance:(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"];
}

- (NSString *)formatDuration:(NSTimeInterval)seconds {
    NSInteger total = (NSInteger)MAX(0, seconds);
    NSInteger hours = total / 3600;
    NSInteger minutes = (total % 3600) / 60;

    if (hours > 0) {
        return [NSString stringWithFormat:@"%ld giờ %ld phút", (long)hours, (long)minutes];
    }
    if (minutes > 0) {
        return [NSString stringWithFormat:@"%ld phút", (long)minutes];
    }
    return [NSString stringWithFormat:@"%ld giây", (long)MAX(1, total)];
}

#pragma mark - Tiện ích

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self searchDestination];
    return YES;
}

- (void)dismissKeyboard {
    [self.view endEditing:YES];
}

@end
