<script lang="ts">
  import { onMount } from 'svelte'
  import { mainpageClick, mainpageGetClick } from '../lib/apis/legacy/mainpage'

  interface Props {
    initialClicks?: number
  }

  let { initialClicks = 0 }: Props = $props()

  // svelte-ignore state_referenced_locally
  let clicks = $state(initialClicks)
  let clicksPending = $state(0)

  onMount(() => {
    // 先 fetch 一次
    mainpageGetClick().then((r) => {
      clicks = r.data
    })

    // 添加计时器
    let _counter = 0
    let itv = setInterval(() => {
      _counter++
      if (clicksPending != 0 && _counter >= 2) {
        _counter = 0

        let _clickPending = clicksPending
        clicks += clicksPending
        clicksPending = 0

        mainpageClick(_clickPending).then((r) => {
          clicks = r.data
        })
      } else {
        if (_counter >= 60) {
          _counter = 0
          mainpageGetClick().then((r) => {
            clicks = r.data
          })
        }
      }
    }, 500)

    return () => {
      clearInterval(itv)
    }
  })

  async function click() {
    clicksPending += 1
  }
</script>

<button class="useless-button" onclick={click}>
  <span class="name">到此一游</span>
  <span class="number">{clicks + clicksPending}</span>
</button>

<style>
  .useless-button {
    display: block;
    background-color: var(--color-bg-n);
    font-size: 1.25rem;
    cursor: pointer;
    border-radius: 1rem;

    overflow: hidden;
    transition: transform ease 0.1s;

    &:hover {
      transform: scale(1.02);
    }

    &:active {
      transform: scale(0.97);
    }

    & > .name {
      display: inline-block;
      font-weight: 300;
      padding-inline-start: 1rem;
      padding-inline-end: 0.5rem;
      padding-block: 0.5rem;
    }

    & > .number {
      display: inline-block;
      padding-inline-start: 0.75rem;
      padding-inline-end: 0.75rem;
      padding-block: 0.5rem;
      background-color: var(--color-green);
      color: var(--color-bg-n);
      font-weight: 600;
    }
  }
</style>
