<script setup>

import { ref, useTemplateRef } from 'vue';
import { marked } from 'marked';
import { Dialog } from '@cloudron/pankow';
import { stripSsoInfo } from '../utils.js';

const dialog = useTemplateRef('dialog');
const app = ref(null);
const hasPendingChecklistItems = ref(false);
const acknowledge = ref(false);

function onConfirm() {
  delete localStorage['confirmPostInstall_' + app.value.id];
  dialog.value.close();
  window.open('https://' + app.value.fqdn);
}

defineExpose({
  async open(a, ack = false) {
    app.value = a;
    acknowledge.value = ack;
    hasPendingChecklistItems.value = !!Object.keys(a.checklist).find((i) => !a.checklist[i].acknowledged);
    dialog.value.open();
  }
});

</script>

<template>
  <Dialog ref="dialog"
    :confirm-label="acknowledge ? $t('app.appInfo.openAction', { app: app.manifest.title }) : null"
    :reject-label="$t('main.dialog.close')"
    :reject-style="acknowledge ? 'secondary' : ''"
    @confirm="onConfirm"
  >
    <div v-if="app">
      <div class="app-info-header">
        <img :src="app.iconUrl" onerror="this.onerror=null;this.src='img/appicon_fallback.png'" class="app-info-icon"/>
        <div class="app-info-title">
          <h2>{{ app.manifest.title }}</h2>
          <span class="text-small">{{ $t('app.appInfo.package') }} v{{ app.manifest.version }}</span>
          <br/>
          <span v-if="app.manifest.documentationUrl" class="text-small"><a target="_blank" :href="app.manifest.documentationUrl">{{ $t('app.docsAction') }}</a></span>
          -
          <span v-if="app.manifest.forumUrl" class="text-small"><a target="_blank" :href="app.manifest.forumUrl">{{ $t('app.forumAction') }}</a></span>
          <br/>
        </div>
      </div>

      <div v-if="app.manifest.postInstallMessage" v-html="marked.parse(stripSsoInfo(app.manifest.postInstallMessage, app.sso))"></div>

      <div class="app-info-checklist" v-show="hasPendingChecklistItems">
        <label class="control-label">{{ $t('app.appInfo.checklist') }}</label>
        <div v-for="(item, key) in app.checklist" :key="key">
          <div class="checklist-item" v-show="!item.acknowledged">
            <span v-html="marked.parse(item.message)"></span>
          </div>
        </div>
      </div>
    </div>
  </Dialog>
</template>

<style scoped>

.app-info-header {
  display: flex;
  margin-bottom: 20px;
}

.app-info-title {
  margin-left: 15px;
}

.app-info-title > h2 {
  margin-top: 0;
  margin-bottom: 0;
}

.app-info-icon {
  width: 64px;
  height: 64px;
}

.app-info-checklist {
  margin-top: 20px;
  margin-bottom: 5px;
}

.checklist-item {
  padding: 8px;
  border: none;
  border-left: 2px solid rgb(255, 76, 76);
  background-color: #ff000014;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.checklist-item > span > * {
  margin: 0;
}

</style>
