<template>
  <v-dialog :model-value="modelValue" max-width="640"
            @update:model-value="$emit('update:modelValue', $event)">
    <v-card v-if="platform">
      <v-card-title>
        Upload {{ platform.name }} {{ platform.auth_type }}
      </v-card-title>
      <v-card-text>
        <v-textarea
          v-if="platform.auth_type === 'cookies'"
          v-model="text"
          label="Netscape cookies.txt content"
          rows="8" auto-grow spellcheck="false"
          :error-messages="error"
          placeholder="# Netscape HTTP Cookie File&#10;.patreon.com&#9;TRUE&#9;/&#9;TRUE&#9;1700000000&#9;session_id&#9;..."
        />
        <v-text-field
          v-else
          v-model="text"
          label="Token"
          type="password"
          :error-messages="error"
        />
        <p v-if="platform.notes" class="text-caption mt-2" style="opacity: 0.75">
          {{ platform.notes }}
        </p>
        <p class="text-caption mt-2" style="opacity: 0.6">
          Tip: the GallerySubscriber browser extension can push this automatically.
        </p>
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn variant="text" @click="$emit('update:modelValue', false)">Cancel</v-btn>
        <v-btn color="accent" variant="flat" :loading="busy" :disabled="!text.trim()" @click="save">
          Save
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useCredentialsStore } from '../../stores/credentials.js'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  platform: { type: Object, default: null },
})
const emit = defineEmits(['update:modelValue', 'saved'])
const store = useCredentialsStore()

const text = ref('')
const error = ref('')
const busy = ref(false)

watch(() => props.modelValue, (open) => {
  if (open) { text.value = ''; error.value = '' }
})

async function save() {
  if (!props.platform) return
  error.value = ''
  if (!text.value.trim()) { error.value = 'Required'; return }
  busy.value = true
  try {
    await store.upload(props.platform.key, props.platform.auth_type, text.value)
    emit('saved')
    emit('update:modelValue', false)
  } catch (e) {
    error.value = String(e?.detail || e?.message || e)
  } finally {
    busy.value = false
  }
}
</script>
