<template>
  <v-dialog v-model="show" max-width="500px" persistent>
    <tos-card>
      <v-card-actions class="justify-space-around mb-8">
        <v-btn variant="elevated" @click="decline" :disabled="!acceptable" prepend-icon="mdi-cancel">Decline</v-btn>
        <v-btn variant="elevated" color="primary" @click="accept" :disabled="!acceptable" prepend-icon="mdi-check">
          Accept
        </v-btn>
      </v-card-actions>
    </tos-card>
  </v-dialog>
</template>

<script setup>
// tos = {
//   version: 1, // Number
//   date: 12345678, // Unix timestamp
//   ip: '123.231.132.213', // IP when client accepted
//   country: 'AD', // https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 Country where the IP is located
// }

import {usePrefStore} from "@/store/store.js";
import {computed, ref, watch} from "vue";

import TosCard from "@/components/TosCard.vue";
import {socket} from "@/socket.js";

// UPDATE THIS WHEN CHANGING THE TOS
const CURRENT_VERSION='2024-11-18'  // this must be a parseable date

const prefs = usePrefStore()
const ok = computed(()=>{
  console.log('check ToS', prefs.acceptedTos)
  return prefs.acceptedTos===CURRENT_VERSION
})
const show = computed(()=>!ok.value)
const acceptable = computed(()=>!inFlight.value)
const inFlight = ref(false)

watch(ok, (newVal, oldVal)=> {console.log('check ToS');if(newVal!==oldVal) console.log('ToS accepted', prefs.acceptedTos, prefs.acceptedTos) })

function accept() {
  inFlight.value = true
  socket.emit('approveTOS', new Date().toISOString(), CURRENT_VERSION, (ok)=>{
    console.log('approve TOS', ok)
    if (ok) prefs.acceptedTos = CURRENT_VERSION
    else console.warn('TOS was not approved')
    inFlight.value = false
  })
}

function decline() {
  // bounce to top-level non-app domain
  window.location.href = 'https://dexorder.trade'
}

</script>

