<script lang="ts">
  import { Class, Doc, DocumentQuery, FindOptions, Ref, Space } from '@hcengineering/core'
  import { IntlString } from '@hcengineering/platform'
  import { AnyComponent, issueSP, Scroller } from '@hcengineering/ui'
  import { BuildModelKey, Viewlet, ViewOptions } from '@hcengineering/view'
  import { onMount } from 'svelte'
  import { ActionContext, ListSelectionProvider, LoadingProps, SelectDirection, selectionStore } from '../..'

  import List from './List.svelte'

  export let _class: Ref<Class<Doc>>
  export let space: Ref<Space> | undefined = undefined
  export let query: DocumentQuery<Doc> = {}
  export let options: FindOptions<Doc> | undefined = undefined
  export let viewlet: Viewlet
  export let config: (string | BuildModelKey)[]
  export let loadingProps: LoadingProps | undefined = undefined
  export let createItemDialog: AnyComponent | undefined
  export let createItemLabel: IntlString | undefined
  export let viewOptions: ViewOptions
  export let props: Record<string, any> = {}

  let list: List

  const listProvider = new ListSelectionProvider((offset: 1 | -1 | 0, of?: Doc, dir?: SelectDirection) => {
    if (dir === 'vertical') {
      // Select next
      list.select(offset, of)
    }
  })

  onMount(() => {
    ;(document.activeElement as HTMLElement)?.blur()
  })
</script>

<ActionContext
  context={{
    mode: 'browser'
  }}
/>

<div class="w-full h-full clear-mins">
  <Scroller fade={issueSP}>
    <List
      bind:this={list}
      {_class}
      {space}
      {query}
      {config}
      {options}
      {loadingProps}
      {createItemDialog}
      {createItemLabel}
      {viewOptions}
      {props}
      viewOptionsConfig={viewlet.viewOptions?.other}
      selectedObjectIds={$selectionStore ?? []}
      on:row-focus={(event) => {
        listProvider.updateFocus(event.detail ?? undefined)
      }}
      on:check={(event) => {
        listProvider.updateSelection(event.detail.docs, event.detail.value)
      }}
      on:content={(evt) => {
        listProvider.update(evt.detail)
      }}
    />
  </Scroller>
</div>
