<template>
  <div class="page-fill">
    <div v-if="pending" class="loading">Loading series details...</div>

    <div v-else-if="error" class="loading">
      <h2>Series Not Found</h2>
      <p>The event series you're looking for doesn't exist.</p>
      <NuxtLink to="/events">&larr; Back to Events</NuxtLink>
    </div>

    <div v-else class="page-fill">
      <!-- BACK LINK -->
      <div class="back-link">
        <NuxtLink to="/events">&larr; Back to Events</NuxtLink>
      </div>

      <!-- SERIES HEADER -->
      <div class="series-header">
        <h1>{{ series.title }}</h1>
        <div class="series-meta-row">
          <span v-if="series.type" class="badge all">{{ formatSeriesType(series.type) }}</span>
          <span class="meta-text">{{ series.events?.length || 0 }} sessions</span>
          <span v-if="series.startDate" class="meta-text">
            {{ formatDate(series.startDate) }} &ndash; {{ formatDate(series.endDate) }}
          </span>
        </div>
      </div>

      <!-- TWO-COLUMN BODY -->
      <div class="series-body" :class="{ 'has-aside': series.tickets?.enabled }">
        <!-- LEFT: MAIN CONTENT -->
        <div class="series-main">
          <div v-if="series.description" class="section description">
            <p>{{ series.description }}</p>
          </div>

          <div class="section" :class="{ 'section-flush': series.events?.length }">
            <div class="section-label">Sessions</div>
            <div v-if="series.events?.length" class="sessions-box">
              <div v-for="(event, index) in series.events" :key="event._id || index" class="event-row">
                <span class="event-num">{{ String(index + 1).padStart(2, '0') }}</span>
                <span class="event-date">{{ formatDate(event.startDate) }}</span>
                <div class="event-info">
                  <div class="event-info-head">
                    <NuxtLink :to="`/events/${event.slug || event._id || event.id}`" class="event-title-link">
                      {{ event.title }}
                    </NuxtLink>
                    <span class="event-status">{{ getEventStatus(event) }}</span>
                  </div>
                  <p v-if="event.description" class="event-description">{{ event.description }}</p>
                </div>
              </div>
            </div>
            <p v-else class="empty">No sessions scheduled yet.</p>
          </div>

          <!-- Questions (inline when no sidebar) -->
          <div v-if="!series.tickets?.enabled" class="section">
            <div class="section-label">Questions?</div>
            <p>If you have questions about this series, reach out to us.</p>
            <a href="mailto:events@ghostguild.org">events@ghostguild.org</a>
          </div>
        </div>

        <!-- RIGHT: SIDEBAR -->
        <aside v-if="series.tickets?.enabled" class="series-aside">
          <SeriesPassPurchase
            :series-id="series.id"
            :series-info="{ id: series.id, title: series.title, totalEvents: series.totalEvents || series.events?.length || 0, type: series.type }"
            :series-events="series.events || []"
            :user-email="memberData?.email"
            :user-name="memberData?.name"
            @purchase-success="handlePurchaseSuccess"
          />

          <div class="aside-panel">
            <div class="box-title">Questions?</div>
            <p class="aside-detail">Drop us a line.</p>
            <a class="aside-link" href="mailto:events@ghostguild.org">events@ghostguild.org</a>
          </div>
        </aside>
      </div>
    </div>
  </div>
</template>

<script setup>
const route = useRoute()
const { memberData } = useAuth()

const { data: series, pending, error } = await useFetch(`/api/series/${route.params.id}`)

if (error.value?.statusCode === 404) {
  throw createError({ statusCode: 404, statusMessage: 'Event series not found' })
}

const formatSeriesType = (type) => {
  const types = { workshop_series: 'Workshop Series', recurring_meetup: 'Recurring Meetup', multi_day: 'Multi-Day Event', course: 'Course', tournament: 'Tournament' }
  return types[type] || type
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
}

const getEventStatus = (event) => {
  const now = new Date()
  const start = new Date(event.startDate)
  const end = new Date(event.endDate)
  if (now < start) return 'Upcoming'
  if (now >= start && now <= end) return 'Ongoing'
  return 'Completed'
}

const handlePurchaseSuccess = () => {
  refreshNuxtData()
}

useSiteMeta(() => ({
  title: series.value ? `${series.value.title} · Event Series` : 'Event Series',
  description:
    series.value?.description ||
    (series.value?.title ? `${series.value.title} — a Ghost Guild event series.` : undefined),
}))
</script>

<style scoped>
.loading { padding: 48px 32px; color: var(--text-dim); }
.loading h2 { font-family: 'Brygada 1918', serif; font-size: 22px; color: var(--text-bright); margin-bottom: 8px; }

.back-link { padding: 12px 32px; border-bottom: 1px dashed var(--border); font-size: 12px; }
.back-link a { color: var(--candle); text-decoration: none; }

.series-header {
  padding: 28px 32px;
  border-bottom: 1px dashed var(--border);
}
.series-header h1 {
  font-family: 'Brygada 1918', serif;
  font-size: 28px;
  font-weight: 600;
  color: var(--text-bright);
  line-height: 1.15;
  margin-bottom: 12px;
}
.series-meta-row {
  display: flex;
  gap: 12px;
  align-items: center;
  font-size: 12px;
}
.meta-text { color: var(--text-faint); }

/* ---- PAGE FILL (aside border reaches viewport bottom) ---- */
.page-fill {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

/* ---- TWO-COLUMN BODY ---- */
.series-body {
  display: grid;
  grid-template-columns: 1fr;
}
.series-body.has-aside {
  grid-template-columns: 1fr 280px;
  flex: 1;
}
.series-main { min-width: 0; }
.series-aside {
  border-left: 1px dashed var(--border);
  padding: 0;
}

.section {
  padding: 24px 32px;
  border-bottom: 1px dashed var(--border);
}
.series-main .section:last-child {
  border-bottom: none;
}
.section p { font-size: 12px; color: var(--text-dim); line-height: 1.7; max-width: 560px; margin-bottom: 8px; }
.section a { font-size: 12px; color: var(--candle); }
.section.description p { font-size: 14px; color: var(--text); }

.section-flush { padding-bottom: 0; }
.sessions-box {
  border-top: 1px dashed var(--border);
  margin: 10px -32px 0;
}
.event-row {
  display: grid;
  grid-template-columns: 32px auto 1fr;
  gap: 12px;
  align-items: baseline;
  padding: 10px 32px;
  border-bottom: 1px dashed var(--border);
  font-size: 12px;
}
.event-row:last-child { border-bottom: none; }
.event-num { color: var(--text-faint); font-size: 11px; }
.event-date { color: var(--text-faint); white-space: nowrap; }
.event-info { min-width: 0; }
.event-title-link { color: var(--text); text-decoration: none; font-size: 13px; }
.event-title-link:hover { color: var(--candle); }
.event-status { font-size: 10px; color: var(--text-faint); margin-left: 8px; }
.event-description {
  font-size: 11px;
  color: var(--text-dim);
  line-height: 1.5;
  margin: 4px 0 0;
  max-width: 560px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.empty { font-size: 12px; color: var(--text-faint); }

/* ---- ASIDE PANELS ---- */
.aside-panel {
  padding: 20px 24px;
  border-bottom: 1px dashed var(--border);
}
.aside-panel:last-child { border-bottom: none; }
.box-title {
  font-size: 10px;
  letter-spacing: 0.1em;
  text-transform: uppercase;
  color: var(--text-faint);
  margin-bottom: 8px;
}
.aside-detail {
  font-size: 12px;
  color: var(--text-dim);
  margin-bottom: 4px;
}
.aside-link {
  font-size: 12px;
  color: var(--candle);
}

@media (max-width: 768px) {
  .series-body.has-aside {
    grid-template-columns: 1fr;
  }
  .series-aside {
    border-left: none;
    border-top: 1px dashed var(--border);
  }
}
</style>
