<script setup>

import { useI18n } from 'vue-i18n';
const i18n = useI18n();
const t = i18n.t;

import { computed, ref, onMounted, watch } from 'vue';
import { fetcher, Button, Switch } from 'pankow';
import { marked } from 'marked';

import Section from  '../components/Section.vue';

const API_ORIGIN = import.meta.env.VITE_API_ORIGIN ? import.meta.env.VITE_API_ORIGIN : window.location.origin;
const accessToken = localStorage.token;

const ready = ref(false);
const sshSupportEnabled = ref(false);
const toggleSshSupportError = ref('');

const description = computed(() => {
  return marked.parse(t('support.help.description', {
    docsLink: 'https://docs.cloudron.io/?support_view',
    packagingLink: 'https://docs.cloudron.io/custom-apps/tutorial/?support_view',
    forumLink: 'https://forum.cloudron.io/'
  }));
});

watch(sshSupportEnabled, async (newValue) => {
  toggleSshSupportError.value = '';

  const res = await fetcher.post(`${API_ORIGIN}/api/v1/support/remote_support`, { enabled: newValue }, { access_token: accessToken });
  if (res.status === 412 || res.status === 417) toggleSshSupportError.value = res.body;
  else if (res.status !== 202) console.error(res.body);
});

onMounted(async () => {
  const response = await fetcher.get(`${API_ORIGIN}/api/v1/support/remote_support`, { access_token: accessToken });
  sshSupportEnabled.value = response.body.enabled;
  ready.value = true;
});

</script>

<template>
  <div class="content">
    <h1 class="section-header">{{ $t('support.title') }}</h1>

    <Section :title="$t('support.help.title')">
      <div v-html="description"></div>
    </Section>

    <Section :title="$t('support.remoteSupport.title')">
      <h2 class="text-center" v-show="!ready"><i class="fa fa-circle-notch fa-spin"></i></h2>
      <div v-show="ready">
        <p>{{ $t('support.remoteSupport.description') }}</p>
        <b>{{ $t('support.remoteSupport.warning') }}</b>
        <br/>
        <br/>
        <b class="pull-left text-danger text-bold" v-show="toggleSshSupportError">{{ toggleSshSupportError }}</b>
        <Switch v-model="sshSupportEnabled" :label="$t(sshSupportEnabled ? 'main.statusEnabled' : 'main.statusDisabled')" />
      </div>
    </Section>
  </div>
</template>
