<script setup lang="ts">
import { computed } from 'vue'
import { messages } from '../lib/messages'
import type { AuthState } from '../lib/models'

const props = defineProps<{ auth: AuthState }>()
defineEmits<{ logout: [] }>()

const logoutLabel = computed(() => {
  if (props.auth.status === 'logging_out') return messages.authStatusLoggingOut
  return messages.authStatusLogOut
})
</script>

<template>
  <span
    v-if="auth.status === 'checking'"
    class="checking"
    :aria-label="messages.authStatusCheckingConnection"
  />
  <a v-else-if="auth.status === 'anonymous'" class="button" href="/api/auth/login">
    <span class="full-label">{{ messages.authStatusConnectSpotify }}</span
    ><span class="short-label">{{ messages.authStatusConnect }}</span>
  </a>
  <span v-else-if="auth.status === 'failed'" class="failed" role="alert">
    <span class="failure-message">{{ auth.message }}</span>
    <a class="button" href="/api/auth/login">
      <span class="full-label">{{ messages.authStatusTryAgain }}</span
      ><span class="short-label">{{ messages.authStatusRetry }}</span>
    </a>
  </span>
  <span v-else class="authenticated">
    <span class="user">
      <span class="dot" aria-hidden="true" />
      <span class="connected">{{ messages.authStatusConnectedAs }}</span
      >{{ auth.user.display_name }}
    </span>
    <button
      class="button"
      type="button"
      :disabled="auth.status === 'logging_out'"
      @click="$emit('logout')"
    >
      {{ logoutLabel }}
    </button>
  </span>
</template>

<style scoped>
.checking {
  width: 116px;
  height: 31px;
  border: 1px solid var(--c-line);
  border-radius: var(--r-pill);
  opacity: 0.55;
}

.authenticated,
.failed {
  display: inline-flex;
  gap: var(--s-3);
  align-items: center;
}

.user {
  display: inline-flex;
  gap: 7px;
  align-items: center;
  padding: 5px 11px;
  color: var(--c-text-muted);
  font-family: var(--f-mono);
  font-size: var(--t-micro);
  border: 1px solid var(--c-line);
  border-radius: var(--r-pill);
}

.dot {
  width: 6px;
  height: 6px;
  background: var(--c-accent);
  border-radius: 50%;
}

.failure-message {
  max-width: 24ch;
  color: var(--c-error);
  font-size: var(--t-micro);
  white-space: normal;
}

.button {
  display: inline-flex;
  flex: none;
  align-items: center;
  min-height: 31px;
  padding: 6px 11px;
  color: var(--c-text-muted);
  font-family: var(--f-mono);
  font-size: var(--t-micro);
  white-space: nowrap;
  cursor: pointer;
  background: transparent;
  border: 1px solid var(--c-line);
  border-radius: var(--r-md);
}

.short-label {
  display: none;
}

.button:hover {
  color: var(--c-text);
  text-decoration: none;
  border-color: var(--c-focus-border);
}

@media (max-width: 760px) {
  .user,
  .failure-message {
    display: none;
  }
}

@media (max-width: 560px) {
  .checking,
  .button {
    min-height: var(--tap-min);
  }

  .full-label {
    display: none;
  }

  .short-label {
    display: inline;
  }
}
</style>
