<template>
  <BaseBottomSheet :model-value="modelValue" label="Share photo" @update:model-value="$emit('update:modelValue', $event)">
    <h2 class="share-sheet__title">Share with someone</h2>
    <p class="share-sheet__sub">They'll get an email and can add it to their frame.</p>

    <div class="share-sheet__field">
      <input
        v-model="email"
        type="email"
        class="share-sheet__input"
        placeholder="their@email.com"
        autocomplete="email"
        @keydown.enter.prevent="submit"
      />
    </div>

    <p v-if="errorMsg" class="share-sheet__error">{{ errorMsg }}</p>
    <p v-if="successMsg" class="share-sheet__success">{{ successMsg }}</p>

    <BaseButton
      variant="primary"
      class="share-sheet__btn"
      :disabled="sending || !email.trim()"
      @click="submit"
    >
      {{ sending ? 'Sending…' : 'Send invite' }}
    </BaseButton>
  </BaseBottomSheet>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import BaseBottomSheet from '@/components/BaseBottomSheet.vue'
import BaseButton from '@/components/BaseButton.vue'
import { useImagesStore } from '@/stores/images'

const props = defineProps<{
  modelValue: boolean
  imageId: number
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', v: boolean): void
}>()

const imagesStore = useImagesStore()
const email       = ref('')
const sending     = ref(false)
const errorMsg    = ref('')
const successMsg  = ref('')

async function submit() {
  errorMsg.value   = ''
  successMsg.value = ''
  if (!email.value.trim()) return
  sending.value = true
  try {
    await imagesStore.shareImage(props.imageId, email.value.trim())
    successMsg.value = `Invite sent to ${email.value.trim()}`
    email.value = ''
  } catch (e) {
    errorMsg.value = e instanceof Error ? e.message : 'Failed to send'
  } finally {
    sending.value = false
  }
}
</script>

<style scoped lang="scss">
.share-sheet {
  &__title { font-size: var(--text-md); font-weight: 700; margin-bottom: var(--space-1); }
  &__sub   { font-size: var(--text-sm); color: var(--color-text-muted); margin-bottom: var(--space-4); }
  &__field { margin-bottom: var(--space-3); }
  &__input {
    width: 100%;
    min-height: var(--touch-min);
    padding: 0 var(--space-3);
    border: 1.5px solid var(--color-border);
    border-radius: var(--radius-md);
    background: var(--color-surface);
    color: var(--color-text);
    font-size: var(--text-sm);
    font-family: inherit;
    &:focus { outline: 2px solid var(--color-primary); outline-offset: 2px; }
  }
  &__error   { font-size: var(--text-sm); color: var(--color-danger, #d93025); margin-bottom: var(--space-3); }
  &__success { font-size: var(--text-sm); color: var(--color-success, #1a7f4b); margin-bottom: var(--space-3); }
  &__btn     { width: 100%; }
}
</style>
