<script setup>
import { ref } from "vue";
import { ClipboardCopyIcon } from "lucide-vue-next";

const password = ref("");
const token = ref("");
const token_element = ref("");

function generate() {
  fetch(`/api/token?password=${password.value}`, { method: "post" })
    .then((e) => {
      if (e.status == 401) {
        alert("Invalid password!");
        return;
      } else if (e.status != 200) {
        alert("Failed requesting API-Token!");
        return;
      }
      return e.json();
    })
    .then((e) => (token.value = e));
}

function copy() {
  const element = token_element.value;
  element.select();
  element.setSelectionRange(0, 99999);
  document.execCommand("copy");
}
</script>

<template>
  <div class="login">
    <h1>{{ $t("token.header") }}</h1>
    <div class="form" v-if="!token">
      <input
        type="password"
        name="password"
        autocomplete="current-password"
        placeholder="Password"
        v-model="password"
      />
      <button type="submit" @click="generate">Generate</button>
    </div>
    <div class="token" @click="copy" v-else>
      <input
        type="text"
        readonly
        ref="token_element"
        v-bind:value="token.token"
      />
      <ClipboardCopyIcon />
    </div>
  </div>
</template>

<style scoped>
.login {
  padding: 50px 10px;
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  font-family: Arial, Helvetica, sans-serif;
  color: var(--text-color);
}

.form {
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: 250px;
}

.form * {
  height: 30px;
}

input {
  border: 0px;
  outline: none;
  background-color: var(--element-color);
  padding: 0px 5px;
  font-size: 15px;
  margin: 5px 0;
  border: 2px solid var(--element-border-input);
  border-radius: 5px;
  transition: 0.2s all;
}

input:hover,
input:focus {
  background-color: var(--element-color-hover);
  border-radius: 8px;
}

button {
  outline: none;
  padding: 5px 5px;
  border: 2px solid var(--element-border-action);
  border-radius: 5px;
  font-size: 15px;
  color: var(--text-color);
  background-color: var(--element-color);
  cursor: pointer;
  transition: 0.2s all;
}

button:hover {
  background-color: var(--element-color-hover);
  border-radius: 8px;
}

.token {
  font-size: 18px;
  padding: 20px;
  border: 2px dashed gray;
  cursor: pointer;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.token input {
  border: unset;
  outline: unset;
  font-size: 16px;
  cursor: pointer;
  font-family: monospace;
  width: 360px;
  max-width: 60vw;
}
</style>
