<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[]>([])

// 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
}

async function onLogoSelect(e: Event) {
  const file = (e.target as HTMLInputElement).files?.[0]
  if (!file) return
  uploadingLogo.value = true
  error.value = null
  try { logoURL.value = await upload(file) }
  catch (e: any) { error.value = useErrMessage(e, 'Logo upload failed') }
  finally { uploadingLogo.value = false }
}

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

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,
      },
    })
  } catch (e: any) {
    error.value = useErrMessage(e, 'Could not save branding')
  } 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="logoURL" class="mt-2 flex items-center gap-2">
              <img :src="logoURL" alt="logo preview" class="h-12 w-12 rounded object-contain bg-zinc-900" />
              <button
                v-if="canEdit"
                type="button"
                class="text-xs text-zinc-500 hover:text-red-300"
                @click="logoURL = ''"
              >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="coverURL" class="mt-2 flex items-center gap-2">
              <img :src="coverURL" alt="cover preview" class="h-12 w-24 rounded object-cover" />
              <button
                v-if="canEdit"
                type="button"
                class="text-xs text-zinc-500 hover:text-red-300"
                @click="coverURL = ''"
              >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="coverURL"
            class="h-28 w-full bg-cover bg-center"
            :style="{ backgroundImage: `url(${coverURL})` }"
          ></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="logoURL" :src="logoURL" alt="" class="h-10 w-10 rounded object-contain bg-zinc-900" />
              <div>
                <p class="text-xs uppercase tracking-widest" :style="{ color: 'var(--brand-primary)' }">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>
            <p v-if="greeting" class="mb-4 text-sm text-zinc-300">{{ 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>
      </div>
    </div>
  </section>
</template>
