<template>
  <v-card
    :variant="hasCredential ? 'outlined' : 'flat'"
    :class="['fc-cred-card', hasCredential && 'fc-cred-card--set']"
  >
    <v-card-title class="d-flex align-center pa-3 ga-2">
      <PlatformChip :platform="platform.key" size="small" />
      <span class="text-body-1">{{ platform.name }}</span>
      <v-spacer />
      <v-chip :color="statusColor" size="x-small" variant="tonal">
        {{ statusLabel }}
      </v-chip>
    </v-card-title>

    <v-card-text class="pa-3 pt-0">
      <template v-if="hasCredential">
        <div class="fc-cred-card__row">
          <v-icon size="small" color="success">mdi-check-circle</v-icon>
          <span>Stored · captured {{ fmtDate(credential.captured_at) }}</span>
        </div>
        <div v-if="credential.expires_at" class="fc-cred-card__row">
          <v-icon size="small" :color="expiringSoon ? 'warning' : 'on-surface-variant'">
            mdi-clock-outline
          </v-icon>
          <span>Expires {{ fmtDate(credential.expires_at) }}</span>
        </div>
        <div v-if="credential.last_verified" class="fc-cred-card__row">
          <v-icon size="small" :color="verifyStale ? 'warning' : 'success'">
            {{ verifyStale ? 'mdi-shield-alert' : 'mdi-shield-check' }}
          </v-icon>
          <span :class="verifyStale ? 'text-warning' : undefined">
            Last verified {{ verifiedRelative }}<template v-if="verifyStale"> — re-verify recommended</template>
          </span>
        </div>
        <div v-else-if="!freshlyVerified" class="fc-cred-card__row">
          <v-icon size="small" color="warning">mdi-shield-alert</v-icon>
          <span class="text-warning">Never verified — click Verify to confirm</span>
        </div>
      </template>
      <template v-else>
        <div class="fc-cred-card__empty">
          <v-icon size="40" color="on-surface-variant" class="fc-cred-card__empty-icon">
            mdi-key-remove
          </v-icon>
          <p class="text-caption text-medium-emphasis">
            No credential stored. Use the extension or paste a {{ platform.auth_type }} below.
          </p>
        </div>
      </template>

      <v-expansion-panels variant="accordion" class="mt-2 fc-cred-card__how">
        <v-expansion-panel>
          <v-expansion-panel-title class="text-caption">
            How to get {{ platform.auth_type }}
          </v-expansion-panel-title>
          <v-expansion-panel-text class="text-caption">
            <slot name="howto">
              <p>{{ howToFallback }}</p>
            </slot>
          </v-expansion-panel-text>
        </v-expansion-panel>
      </v-expansion-panels>
    </v-card-text>

    <v-card-actions class="px-3 pb-3 pt-0">
      <v-chip
        v-if="verifyResult"
        :color="verifyResult.valid === true ? 'success' : (verifyResult.valid === false ? 'error' : 'grey')"
        size="x-small" variant="tonal" class="me-auto"
        :title="verifyResult.reason"
      >{{ verifyChipLabel }}</v-chip>
      <v-spacer v-else />
      <v-btn
        v-if="hasCredential"
        size="small" variant="text"
        :loading="verifying"
        @click="onVerify"
      >
        Verify
      </v-btn>
      <v-btn
        v-if="hasCredential"
        size="small" variant="text" color="error"
        @click="$emit('remove', platform)"
      >
        Remove
      </v-btn>
      <v-btn
        size="small"
        :variant="hasCredential ? 'outlined' : 'flat'"
        :color="hasCredential ? undefined : 'accent'"
        @click="$emit('replace', platform)"
      >
        {{ hasCredential ? 'Update' : 'Add credentials' }}
      </v-btn>
    </v-card-actions>
  </v-card>
</template>

<script setup>
import { toast } from '../../utils/toast.js'
import { computed, ref } from 'vue'
import PlatformChip from './PlatformChip.vue'
import { useCredentialsStore } from '../../stores/credentials.js'
import { formatLocalDate } from '../../utils/date.js'

const props = defineProps({
  platform: { type: Object, required: true },
  credential: { type: Object, default: null },
})
const emit = defineEmits(['replace', 'remove', 'verified'])

const credsStore = useCredentialsStore()
const verifying = ref(false)
const verifyResult = ref(null)

const verifyChipLabel = computed(() => {
  if (!verifyResult.value) return ''
  if (verifyResult.value.valid === true) return 'Verified ✓'
  if (verifyResult.value.valid === false) return 'Failed'
  return 'Untestable'
})

async function onVerify() {
  verifying.value = true
  verifyResult.value = null
  try {
    const res = await credsStore.verify(props.platform.key)
    verifyResult.value = res
    const type = res.valid === true ? 'success' : (res.valid === false ? 'error' : 'info')
    toast({ text: `${props.platform.name}: ${res.reason}`, type })
    if (res.valid === true) emit('verified')
  } catch (e) {
    verifyResult.value = { valid: false, reason: e.message }
    toast({ text: `Verify failed: ${e.message}`, type: 'error' })
  } finally {
    verifying.value = false
  }
}

const hasCredential = computed(() => !!props.credential)

// Within 7 days = expiring soon. The backend doesn't set hard rotation
// policy yet; this just nudges the operator with a warning chip.
const expiringSoon = computed(() => {
  const exp = props.credential?.expires_at
  if (!exp) return false
  const diff = (new Date(exp).getTime() - Date.now()) / 86400_000
  return diff > 0 && diff < 7
})

// Verification staleness: a stored cookie/token that hasn't been confirmed
// in a month is the silent-failure trap (subscribestar/HF). Nudge the
// operator to re-verify before a scheduled download dies on bad auth.
const STALE_DAYS = 30
// A successful Verify in this session clears the warning even before the
// parent reloads the credential list (last_verified prop is still old).
const freshlyVerified = computed(() => verifyResult.value?.valid === true)
const verifiedAgeDays = computed(() => {
  const v = props.credential?.last_verified
  if (!v) return null
  return (Date.now() - new Date(v).getTime()) / 86400_000
})
const verifyStale = computed(() => {
  if (!hasCredential.value || freshlyVerified.value) return false
  const age = verifiedAgeDays.value
  return age == null || age > STALE_DAYS
})
const verifiedRelative = computed(() => {
  const age = verifiedAgeDays.value
  if (age == null) return '—'
  if (age < 1) return 'today'
  if (age < 2) return 'yesterday'
  if (age < 30) return `${Math.floor(age)}d ago`
  if (age < 365) return `${Math.floor(age / 30)}mo ago`
  return `${Math.floor(age / 365)}y ago`
})

const statusLabel = computed(() => {
  if (!hasCredential.value) return 'Not configured'
  if (expiringSoon.value) return 'Expiring soon'
  if (verifyStale.value) return 'Verify due'
  return 'Active'
})
const statusColor = computed(() => {
  if (!hasCredential.value) return 'grey'
  if (expiringSoon.value || verifyStale.value) return 'warning'
  return 'success'
})

const howToFallback = computed(() => {
  if (props.platform.auth_type === 'cookies') {
    return 'Use the FabledCurator browser extension on the platform page, or export cookies.txt and paste here.'
  }
  return 'Paste the access token from your account settings.'
})

function fmtDate(iso) {
  return iso ? formatLocalDate(iso) : '—'
}
</script>

<style scoped>
.fc-cred-card {
  border: 1px dashed rgb(var(--v-theme-on-surface-variant) / 0.3);
  background: rgb(var(--v-theme-surface));
  height: 100%;
}
.fc-cred-card--set {
  border-style: solid;
  border-color: rgb(var(--v-theme-accent) / 0.5);
}
.fc-cred-card__row {
  display: flex; gap: 6px; align-items: center;
  font-size: 0.9rem;
  margin-top: 4px;
  color: rgb(var(--v-theme-on-surface));
}
.fc-cred-card__empty {
  display: flex; flex-direction: column; align-items: center; gap: 8px;
  padding: 12px 0;
  text-align: center;
}
.fc-cred-card__empty-icon { opacity: 0.5; }
.fc-cred-card__how :deep(.v-expansion-panel) {
  background: transparent;
}
</style>
