generate_nps_splits <- function(x) {
  nps_split_m <- input$nps_split_km * 1000
  if (input$nps_split_km == 0) {
    nps_split_m <- 1000000
  }

  x$nps_split_km <- nps_split_m / 1000

  suppressWarnings(
    nps_points <- x$segmentized_points %>%
      inner_join(x$valid_transects, by = c("Date", "TripID", "Transect")) %>%
      st_transform(x$crs) %>%
      filter(!is.na(TripID), !is.na(Transect), !is.na(Date), !is.na(rleid)) %>%
      mutate(
        x = map_dbl(geometry, ~ st_centroid(.x)[[1]]),
        y = map_dbl(geometry, ~ st_centroid(.x)[[2]])
      ) %>%
      group_by(TripID, Transect, Date) %>%
      arrange(TripID, Transect, timestamp) %>%
      mutate(
        next_m = if_else(rleid == lead(rleid),
          sqrt(((lead(x) - x)**2) + (lead(y) - y)**2),
          0
        ),
        cumsum_m = cumsum(next_m),
        split_id = floor(cumsum_m / nps_split_m),
        max_split_id = max(split_id, na.rm = TRUE),
        split_id = coalesce(split_id, max_split_id),
        split_id = if_else(split_id == max_split_id & max_split_id > 0,
          split_id - 1,
          split_id
        )
      )
  )

  next_points <- nps_points %>%
    group_by(TripID, Transect, Date, rleid) %>%
    mutate(prev_point_id = lag(split_id)) %>%
    filter(split_id != prev_point_id) %>%
    mutate(split_id = prev_point_id) %>%
    select(-prev_point_id)

  nps_split <- nps_points %>%
    bind_rows(next_points) %>%
    group_by(TripID, Transect, Date, rleid, split_id) %>%
    summarize(
      do_union = FALSE,
      start_time = min(timestamp),
      end_time = max(timestamp),
      .groups = "drop"
    ) %>%
    st_cast("LINESTRING")

  nps_split$vertices <- nps_split %>%
    st_coordinates() %>%
    as_tibble() %>%
    group_by(L1) %>%
    summarize(
      n = n(),
      .groups = "drop"
    ) %>%
    pull(n)

  nps_split <- nps_split %>%
    filter(vertices > 1) %>%
    group_by(TripID, Transect, Date, split_id) %>%
    # select(-do_union) %>%
    summarize(
      do_union = FALSE,
      start_time = min(start_time),
      end_time = max(end_time),
      .groups = "drop"
    ) %>%
    st_cast("MULTILINESTRING") %>%
    st_transform(x$crs) %>%
    mutate(length_km = map_dbl(geometry, ~ st_length(.x)) / 1000) %>%
    st_transform(4326)

  x$nps_split <- nps_split

  nps_track_centroids <- nps_points %>%
    group_by(TripID, Transect, Date, split_id) %>%
    summarize(.groups = "drop") %>%
    mutate(
      x = map_dbl(geometry, ~ st_centroid(.x)[[1]]),
      y = map_dbl(geometry, ~ st_centroid(.x)[[2]])
    ) %>%
    st_drop_geometry() %>%
    st_as_sf(coords = c("x", "y"), crs = x$crs) %>%
    st_transform(4326) %>%
    mutate(
      Latitude = map_dbl(geometry, ~ st_centroid(.x)[[2]]),
      Longitude = map_dbl(geometry, ~ st_centroid(.x)[[1]])
    )

  x$nps_track_centroids <- nps_track_centroids

  x
}
