<script lang="ts">
  /**
   * Element that labels the GPS state
   */
  import { fade } from "svelte/transition"
  import ThemeViewState from "../../Models/ThemeViewState"
  import Tr from "../Base/Tr.svelte"
  import { onDestroy } from "svelte"
  import { Popover } from "flowbite-svelte"

  export let state: ThemeViewState
  let gpsState = state.geolocationState
  export let mapIsDragged: Store<void>
  let open = true

  function showFor(timeoutSeconds: number = 5) {
    console.trace("Showing for", timeoutSeconds)
    open = true
    window.setTimeout(() => {
        open = false
      },
      timeoutSeconds * 1000)
  }

  mapIsDragged.addCallback(() => {
    const movingIsAllowed = gpsState.allowMoving.data
    if (!movingIsAllowed) {
      showFor(5)
    }
  })
  gpsState.requestMoment.stabilized(50).addCallback(() => {
    if(gpsState.gpsAvailable.data && gpsState.allowMoving.data){
      return
    }
    showFor(5)
  })
  let explanation = gpsState.gpsStateExplanation
  onDestroy(
    explanation.addCallbackD(
      expl => {
        if (expl) {
          showFor(5)
        } else {
          open = false
        }
      },
    ),
  )

</script>

<Popover reference={undefined} trigger=null placement="left" transition={e => fade(e, {duration: 150})} bind:open>
  <div class="break-words" style="max-width: calc( 100vw - 8rem)">
    <Tr t={$explanation} />
  </div>
</Popover>
