bind m-4 run -C '#{@layout-vertical-two}'

set -g @layout-vertical-two {
  selectl main-vertical
  if -F '#{==:#{@vertical-two-active},true}' {
    set -wu @vertical-two-active
  } {
    if -F '#{&&:#{==:#{N/s:layout_overflow},0},#{e|>=:#{n:#{P:x}},3}}' {
      run -C '#{@layout-vertical-two-init}'
    }
  }
}

set -g @layout-vertical-two-init {
  set -gF @total_panes '#{n:#{P:x}}'
  set -gF @cur_window '#S:#I'
  new -ds layout_overflow
  run -C '\
    swapw -t layout_overflow: -s . ;\
    splitw -fh -l 40% -t #{@cur_window} ;\
    splitw  -h        -t #{@cur_window}.2 ;\
    swapp -s #{@cur_window}.1 -t layout_overflow:1.1 ; killp -t layout_overflow:1.1 ;\
    swapp -s #{@cur_window}.2 -t layout_overflow:1.1 ; killp -t layout_overflow:1.1 ;\
    swapp -s #{@cur_window}.3 -t layout_overflow:1.1 ; killp -t layout_overflow:1.1 ;\
    #{@layout-vertical-two-loop}'
}

set -g @layout-vertical-two-cleanup {
  set -gu @cur_window
  set -gu @total_panes '#{n:#{P:x}}'
  set -w @vertical-two-active true
  selectp -t .1
}

# (x - 1) % 2 == 0 ? (x - 1) / 2 + 1 : x
# #{?#{==:#{e|%:#{e|-:#{cur_panes},1},2},0}  <-- TODO: inserting horizontally shuffles windows.
#  ,#{e|+:#{e|/:#{e|-:#{cur_panes},1},2},1}  <-- end of first column
#  ,#{cur_panes}}                            <-- end of second column
set -g @layout-vertical-two-loop {
  # count(panes) < count(original.panes)
  if -F '#{e|<:#{n:#{P:x}},#{@total_panes}}' {
    run -C "joinp -s layout_overflow:1.1 -vt '#{@cur_window}.#{?#{==:#{e|%:#{e|-:#{#{n:#{P:x}}},1},2},0},#{e|+:#{e|/:#{e|-:#{#{n:#{P:x}}},1},2},1},#{#{n:#{P:x}}}}' ;\
    selectl -E ; #{@layout-vertical-two-loop}"
  } {
    run -C '#{@layout-vertical-two-cleanup}'
  }
}
