generate_nppsd_splits <- function(x) {
  if (input$use_nps_length_for_nppsd) {
    nppsd_split_m <- input$nps_split_km * 1000
  } else {
    nppsd_split_m <- 3300
  }

  x$nppsd_split_km <- nppsd_split_m / 1000

  suppressWarnings(
    nppsd_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),
        nppsd_split_id = floor(cumsum_m / nppsd_split_m),
        max_split_id = max(nppsd_split_id, na.rm = TRUE),
        nppsd_split_id = coalesce(nppsd_split_id, max_split_id),
        nppsd_split_id = if_else(
          nppsd_split_id == max_split_id & max_split_id > 0,
          nppsd_split_id - 1,
          nppsd_split_id
        )
      )
  )

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

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

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

  nppsd_split <- nppsd_split %>%
    filter(vertices > 1) %>%
    group_by(TripID, Transect, Date, nppsd_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$nppsd_split <- nppsd_split

  nppsd_track_centroids <- nppsd_points %>%
    group_by(TripID, Transect, Date, nppsd_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$nppsd_track_centroids <- nppsd_track_centroids

  x
}
