<script setup lang="ts">
// Tier 2 Block D — per-event branding editor. Editor+ only; we hide the
// inputs for viewers (the server enforces the role too).
//
// Live preview happens client-side: we don't PUT until the host hits Save,
// but the colours/logo/cover update the preview pane on every change so
// they see what their guests will see before committing.

interface Branding {
  event_id: string
  primary_color?: string | null
  accent_color?: string | null
  logo_url?: string | null
  cover_image_url?: string | null
  font_family?: string | null
  greeting_message?: string | null
  updated_at?: string
}

interface BrandingResponse {
  event_id: string
  primary_color?: string | null
  accent_color?: string | null
  logo_url?: string | null
  cover_image_url?: string | null
  font_family?: string | null
  greeting_message?: string | null
  allowed_fonts: string[]
}

const props = defineProps<{
  eventId: string
  yourRole?: 'owner' | 'editor' | 'viewer' | null
  // Event name + date are echoed in the preview so the host sees the
  // composed page, not just the colour swatches.
  eventName?: string
  eventVenue?: string
  eventDate?: string
}>()

const config = useRuntimeConfig()
const auth = useAuth()

const loading = ref(true)
const saving = ref(false)
const error = ref<string | null>(null)
const allowedFonts = ref<string[]>([])

// Toast state — auto-dismisses after a few seconds; the user can also
// click it to dismiss. Kind drives the colour: success = brand-green,
// error = red. We keep this local to the component rather than reaching
// for a global toast system (the same inline pattern is used on the
// account + billing pages already).
type Toast = { kind: 'success' | 'error'; text: string }
const toast = ref<Toast | null>(null)
let toastTimer: ReturnType<typeof setTimeout> | null = null
function showToast(t: Toast, ms = 4000) {
  toast.value = t
  if (toastTimer) clearTimeout(toastTimer)
  toastTimer = setTimeout(() => { toast.value = null }, ms)
}

// Form state — strings so empty maps cleanly to "clear this field".
const primary = ref('')
const accent = ref('')
const logoURL = ref('')
const coverURL = ref('')
const font = ref('')
const greeting = ref('')

const canEdit = computed(() => props.yourRole === 'owner' || props.yourRole === 'editor')

async function refresh() {
  loading.value = true
  try {
    const data = await useApi<BrandingResponse>(`/events/${props.eventId}/branding`)
    allowedFonts.value = data.allowed_fonts || []
    primary.value = data.primary_color ?? ''
    accent.value = data.accent_color ?? ''
    logoURL.value = data.logo_url ?? ''
    coverURL.value = data.cover_image_url ?? ''
    font.value = data.font_family ?? ''
    greeting.value = data.greeting_message ?? ''
  } catch (e: any) {
    error.value = useErrMessage(e, 'Could not load branding')
  } finally {
    loading.value = false
  }
}
onMounted(refresh)

// --- uploads ---
const uploadingLogo = ref(false)
const uploadingCover = ref(false)

async function upload(file: File): Promise<string> {
  const apiBase = config.public.apiBase as string
  const token = auth.liveAccessToken()
  const form = new FormData()
  form.append('file', file)
  const res = await fetch(`${apiBase}/uploads/image`, {
    method: 'POST',
    headers: token ? { Authorization: `Bearer ${token}` } : {},
    credentials: 'include',
    body: form,
  })
  if (!res.ok) {
    let msg = `HTTP ${res.status}`
    try { msg = (await res.json()).error || msg } catch { /* no body */ }
    throw new Error(msg)
  }
  const json = await res.json()
  return json.url as string
}

// Object URLs for the file the user just picked, shown in the preview
// pane while the upload is in flight. Once the server returns its real
// URL we swap to that and revoke the temporary one. Without this the
// preview stays empty until the round-trip completes, which feels broken
// even when uploads are fast.
const logoObjectURL = ref<string | null>(null)
const coverObjectURL = ref<string | null>(null)

function revokeIf(u: string | null) {
  if (u) URL.revokeObjectURL(u)
}

async function onLogoSelect(e: Event) {
  const file = (e.target as HTMLInputElement).files?.[0]
  if (!file) return
  revokeIf(logoObjectURL.value)
  logoObjectURL.value = URL.createObjectURL(file)
  uploadingLogo.value = true
  error.value = null
  try {
    logoURL.value = await upload(file)
  } catch (e: any) {
    error.value = useErrMessage(e, 'Logo upload failed')
    // Roll back the local preview so the host doesn't think the upload
    // succeeded when it didn't.
    revokeIf(logoObjectURL.value)
    logoObjectURL.value = null
  } finally {
    uploadingLogo.value = false
  }
}

async function onCoverSelect(e: Event) {
  const file = (e.target as HTMLInputElement).files?.[0]
  if (!file) return
  revokeIf(coverObjectURL.value)
  coverObjectURL.value = URL.createObjectURL(file)
  uploadingCover.value = true
  error.value = null
  try {
    coverURL.value = await upload(file)
  } catch (e: any) {
    error.value = useErrMessage(e, 'Cover upload failed')
    revokeIf(coverObjectURL.value)
    coverObjectURL.value = null
  } finally {
    uploadingCover.value = false
  }
}

// Resolved URLs the preview pane consumes. Prefer the server URL once it's
// landed; while the upload is in flight we show the local object URL so
// the host sees their image straight away.
const logoPreviewURL = computed(() => logoURL.value || logoObjectURL.value || '')
const coverPreviewURL = computed(() => coverURL.value || coverObjectURL.value || '')

onUnmounted(() => {
  revokeIf(logoObjectURL.value)
  revokeIf(coverObjectURL.value)
})

async function save() {
  saving.value = true
  error.value = null
  try {
    await useApi(`/events/${props.eventId}/branding`, {
      method: 'PUT',
      body: {
        primary_color: primary.value,
        accent_color: accent.value,
        logo_url: logoURL.value,
        cover_image_url: coverURL.value,
        font_family: font.value,
        greeting_message: greeting.value,
      },
    })
    showToast({ kind: 'success', text: 'Branding saved.' })
  } catch (e: any) {
    const msg = useErrMessage(e, 'Could not save branding')
    error.value = msg
    showToast({ kind: 'error', text: msg })
  } finally {
    saving.value = false
  }
}

// Preview style — drives both the colour swatches and the mini RSVP
// card preview underneath. Reactive on every input so the host sees
// changes immediately, even before clicking Save.
const previewStyle = computed(() => ({
  '--brand-primary': primary.value || '#22c55e',
  '--brand-accent': accent.value || '#15803d',
  fontFamily: font.value || 'inherit',
}))

function fmtDate(iso?: string) {
  if (!iso) return ''
  try { return new Date(iso).toLocaleString() } catch { return iso }
}
</script>

<template>
  <section class="card">
    <header class="mb-3 flex items-center justify-between">
      <h2 class="text-lg font-semibold">Branding</h2>
      <button
        v-if="canEdit"
        type="button"
        class="btn-primary text-sm"
        :disabled="saving"
        @click="save"
      >{{ saving ? 'Saving…' : 'Save branding' }}</button>
    </header>
    <p class="mb-4 text-xs text-zinc-500">
      Customise how your invitation page looks. Colours, font, logo, and cover image apply to
      every guest's RSVP page.
    </p>

    <p v-if="error" class="mb-3 text-sm text-red-400">{{ error }}</p>
    <p v-if="loading" class="text-sm text-zinc-500">Loading branding…</p>

    <div v-else class="grid grid-cols-1 gap-6 lg:grid-cols-2">
      <!-- Editor -->
      <div class="space-y-4">
        <div class="grid grid-cols-2 gap-3">
          <div>
            <label class="label">Primary colour</label>
            <div class="flex items-center gap-2">
              <input
                v-model="primary"
                type="color"
                class="h-10 w-12 cursor-pointer rounded border border-zinc-700 bg-zinc-900 disabled:opacity-50"
                :disabled="!canEdit"
              />
              <input
                v-model="primary"
                type="text"
                placeholder="#22c55e"
                class="input flex-1 font-mono text-xs"
                :disabled="!canEdit"
              />
            </div>
          </div>
          <div>
            <label class="label">Accent colour</label>
            <div class="flex items-center gap-2">
              <input
                v-model="accent"
                type="color"
                class="h-10 w-12 cursor-pointer rounded border border-zinc-700 bg-zinc-900 disabled:opacity-50"
                :disabled="!canEdit"
              />
              <input
                v-model="accent"
                type="text"
                placeholder="#15803d"
                class="input flex-1 font-mono text-xs"
                :disabled="!canEdit"
              />
            </div>
          </div>
        </div>

        <div>
          <label class="label">Font family</label>
          <select v-model="font" class="input" :disabled="!canEdit">
            <option value="">Default (Inter)</option>
            <option v-for="f in allowedFonts" :key="f" :value="f">{{ f }}</option>
          </select>
        </div>

        <div>
          <label class="label">Greeting message (shown above the form)</label>
          <textarea
            v-model="greeting"
            class="input min-h-[72px]"
            placeholder="Looking forward to celebrating with you!"
            :disabled="!canEdit"
          />
        </div>

        <div class="grid grid-cols-2 gap-3">
          <div>
            <label class="label">Logo</label>
            <input
              type="file"
              accept="image/png,image/jpeg"
              class="block w-full text-xs text-zinc-400 file:mr-2 file:rounded file:border-0 file:bg-zinc-800 file:px-2 file:py-1 file:text-zinc-200 file:cursor-pointer"
              :disabled="!canEdit || uploadingLogo"
              @change="onLogoSelect"
            />
            <div v-if="logoPreviewURL" class="mt-2 flex items-center gap-2">
              <img :src="logoPreviewURL" alt="logo preview" class="h-12 w-12 rounded object-contain bg-zinc-900" />
              <span v-if="uploadingLogo" class="text-xs text-zinc-500">Uploading…</span>
              <button
                v-if="canEdit && !uploadingLogo"
                type="button"
                class="text-xs text-zinc-500 hover:text-red-300"
                @click="logoURL = ''; revokeIf(logoObjectURL); logoObjectURL = null"
              >Remove</button>
            </div>
          </div>
          <div>
            <label class="label">Cover image</label>
            <input
              type="file"
              accept="image/png,image/jpeg"
              class="block w-full text-xs text-zinc-400 file:mr-2 file:rounded file:border-0 file:bg-zinc-800 file:px-2 file:py-1 file:text-zinc-200 file:cursor-pointer"
              :disabled="!canEdit || uploadingCover"
              @change="onCoverSelect"
            />
            <div v-if="coverPreviewURL" class="mt-2 flex items-center gap-2">
              <img :src="coverPreviewURL" alt="cover preview" class="h-12 w-24 rounded object-cover" />
              <span v-if="uploadingCover" class="text-xs text-zinc-500">Uploading…</span>
              <button
                v-if="canEdit && !uploadingCover"
                type="button"
                class="text-xs text-zinc-500 hover:text-red-300"
                @click="coverURL = ''; revokeIf(coverObjectURL); coverObjectURL = null"
              >Remove</button>
            </div>
          </div>
        </div>

        <p class="text-xs text-zinc-500">
          Images: PNG or JPEG, up to 2 MB. They're re-encoded server-side so EXIF data is stripped.
        </p>
      </div>

      <!-- Live preview -->
      <div>
        <p class="mb-2 text-xs font-medium uppercase tracking-wider text-zinc-500">Preview</p>
        <div
          class="overflow-hidden rounded-lg border border-zinc-800 bg-zinc-950"
          :style="previewStyle"
        >
          <div
            v-if="coverPreviewURL"
            class="h-28 w-full bg-cover bg-center"
            :style="{ backgroundImage: `url(${coverPreviewURL})` }"
          ></div>
          <div v-else class="h-28 w-full" :style="{ background: 'var(--brand-primary)' }"></div>
          <div class="p-4">
            <div class="mb-3 flex items-center gap-3">
              <img v-if="logoPreviewURL" :src="logoPreviewURL" alt="" class="h-10 w-10 rounded object-contain bg-zinc-900" />
              <div>
                <!-- Eyebrow text uses the accent colour — visible on
                     every page, gives the host immediate feedback that
                     their accent choice landed. -->
                <p class="text-xs uppercase tracking-widest" :style="{ color: 'var(--brand-accent)' }">Invitation</p>
                <h3 class="text-xl font-semibold text-zinc-50">{{ eventName || 'Your event name' }}</h3>
              </div>
            </div>
            <p class="mb-3 text-xs text-zinc-400">
              {{ eventVenue || 'Venue' }} · {{ fmtDate(eventDate) || 'When' }}
            </p>
            <!-- Greeting takes a 3px accent-colour left border so the
                 accent shows up even when the host hasn't customised
                 the message itself. -->
            <p
              v-if="greeting"
              class="mb-4 rounded-r border-l-[3px] bg-zinc-900/40 py-1.5 pl-3 pr-2 text-sm text-zinc-300"
              :style="{ borderColor: 'var(--brand-accent)' }"
            >{{ greeting }}</p>
            <button
              type="button"
              class="w-full rounded-md px-3 py-2 text-sm font-medium text-zinc-950"
              :style="{ background: 'var(--brand-primary)' }"
              disabled
            >Submit RSVP</button>
          </div>
        </div>
        <p class="mt-2 text-xs text-zinc-500">
          Primary fills the main button; accent picks out the eyebrow + greeting border.
        </p>
      </div>
    </div>

    <!-- Save feedback toast. Teleported to body so the fixed positioning
         isn't trapped by the card's stacking context. Click to dismiss
         early; auto-fades after 4s. -->
    <Teleport to="body">
      <Transition
        enter-active-class="transition duration-200 ease-out"
        enter-from-class="translate-y-2 opacity-0"
        enter-to-class="translate-y-0 opacity-100"
        leave-active-class="transition duration-200 ease-in"
        leave-from-class="translate-y-0 opacity-100"
        leave-to-class="translate-y-2 opacity-0"
      >
        <button
          v-if="toast"
          type="button"
          class="fixed bottom-6 right-6 z-50 flex max-w-sm items-center gap-2 rounded-lg border px-4 py-3 text-left text-sm shadow-lg backdrop-blur"
          :class="toast.kind === 'success'
            ? 'border-brand-700/60 bg-brand-950/90 text-brand-100'
            : 'border-red-800/60 bg-red-950/90 text-red-100'"
          :aria-live="toast.kind === 'error' ? 'assertive' : 'polite'"
          role="status"
          @click="toast = null"
        >
          <svg v-if="toast.kind === 'success'" class="h-4 w-4 shrink-0 text-brand-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
            <path fill-rule="evenodd" d="M16.704 5.296a1 1 0 010 1.408l-8 8a1 1 0 01-1.408 0l-4-4a1 1 0 011.408-1.408L8 12.592l7.296-7.296a1 1 0 011.408 0z" clip-rule="evenodd" />
          </svg>
          <svg v-else class="h-4 w-4 shrink-0 text-red-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
            <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zM10 5a1 1 0 011 1v4a1 1 0 11-2 0V6a1 1 0 011-1zm0 8.5a1.25 1.25 0 110 2.5 1.25 1.25 0 010-2.5z" clip-rule="evenodd" />
          </svg>
          <span>{{ toast.text }}</span>
        </button>
      </Transition>
    </Teleport>
  </section>
</template>
