<template>
  <div class="dashboard">
    <!-- Loading State -->
    <div v-if="authPending" class="loading-state">
      <div class="spinner" />
      <p>Loading your dashboard...</p>
    </div>

    <!-- Unauthenticated State -->
    <div v-else-if="!memberData" class="unauth-state">
      <h2>Sign in required</h2>
      <p>Please sign in to access your member dashboard.</p>
      <button
        class="btn btn-primary"
        @click="openLoginModal({ title: 'Sign in to your dashboard', description: 'Enter your email to access your member dashboard' })"
      >
        Sign In
      </button>
    </div>

    <!-- Dashboard Content -->
    <template v-else>
      <!-- Member Status Banner -->
      <MemberStatusBanner :dismissible="true" />

      <!-- Welcome Header -->
      <div class="welcome">
        <h1>Welcome back, {{ memberData?.name }}</h1>
        <div class="meta">
          <CircleBadge :circle="memberData?.circle || 'community'" />
          <span>${{ memberData?.contributionTier }} CAD/mo</span>
        </div>
      </div>

      <!-- Upcoming Events + Quick Actions -->
      <div class="content-row">
        <div class="content-block">
          <div class="section-label">Your Upcoming Events</div>

          <div v-if="loadingEvents" class="loading-inline">
            <div class="spinner spinner-sm" />
          </div>

          <div v-else-if="registeredEvents.length" class="event-list">
            <NuxtLink
              v-for="evt in registeredEvents"
              :key="evt._id"
              :to="`/events/${evt.slug || evt._id}`"
              class="event-item"
            >
              <span class="event-date">{{ formatEventDate(evt.startDate) }}</span>
              <span class="event-title">{{ evt.title }}</span>
              <CircleBadge v-if="evt.circle" :circle="evt.circle" />
            </NuxtLink>

            <!-- Calendar subscription -->
            <button class="calendar-btn" @click="copyCalendarLink">
              {{ calendarLinkCopied ? 'Link copied!' : 'Subscribe to calendar' }}
            </button>
          </div>

          <div v-else class="empty-state">
            <p>You haven't registered for any upcoming events</p>
          </div>

          <NuxtLink to="/events" class="section-link">Browse all events &rarr;</NuxtLink>

          <!-- Calendar subscription instructions -->
          <div v-if="registeredEvents.length > 0 && showCalendarInstructions" class="calendar-instructions">
            <div class="ci-header">
              <strong>How to Subscribe to Your Calendar</strong>
              <button @click="showCalendarInstructions = false" class="ci-close">&times;</button>
            </div>
            <ul>
              <li><strong>Google Calendar:</strong> Click "+" then "From URL" then paste the link</li>
              <li><strong>Apple Calendar:</strong> File then New Calendar Subscription then paste the link</li>
              <li><strong>Outlook:</strong> Add Calendar then Subscribe from web then paste the link</li>
            </ul>
            <p class="ci-note">Your calendar will automatically update when you register or unregister from events.</p>
          </div>
        </div>

        <div class="content-block">
          <div class="section-label">Quick Actions</div>
          <NuxtLink
            to="/members?peerSupport=true"
            class="quick-action"
            :class="{ disabled: !canPeerSupport }"
            :title="!canPeerSupport ? 'Complete your membership to book peer sessions' : ''"
          >
            Book a peer session<span class="arrow">&rarr;</span>
          </NuxtLink>
          <NuxtLink to="/member/profile" class="quick-action">
            Update your profile<span class="arrow">&rarr;</span>
          </NuxtLink>
          <a href="https://wiki.ghostguild.org" target="_blank" class="quick-action">
            Browse the wiki<span class="arrow">&rarr;</span>
          </a>
          <NuxtLink to="/members" class="quick-action">
            Browse members<span class="arrow">&rarr;</span>
          </NuxtLink>
          <NuxtLink to="/member/profile#account" class="quick-action">
            Manage account<span class="arrow">&rarr;</span>
          </NuxtLink>
        </div>
      </div>

      <!-- Membership Summary + Peer Support -->
      <div class="content-row">
        <div class="content-block">
          <div class="section-label">Your Membership</div>
          <div class="membership-row">
            <span class="key">Circle</span>
            <span class="val" :style="{ color: `var(--c-${memberData?.circle || 'community'})` }">
              {{ memberData?.circle }}
            </span>
          </div>
          <div class="membership-row">
            <span class="key">Contribution</span>
            <span class="val">${{ memberData?.contributionTier }} CAD/month</span>
          </div>
          <div class="membership-row">
            <span class="key">Status</span>
            <span class="val">
              <span :class="isActive ? 'status-active' : ''">
                {{ isActive ? 'Active' : statusConfig.label }}
              </span>
            </span>
          </div>
          <div v-if="memberData?.createdAt" class="membership-row">
            <span class="key">Member since</span>
            <span class="val">{{ formatMemberSince(memberData.createdAt) }}</span>
          </div>
          <NuxtLink to="/member/profile#account" class="section-link">
            Change circle or contribution &rarr;
          </NuxtLink>
        </div>

        <div class="content-block">
          <div class="section-label">Peer Support</div>
          <DashedBox>
            <p class="peer-text">
              Interested in offering peer support? Set up your profile to connect with other members who share your interests and experience.
            </p>
            <NuxtLink to="/member/profile" class="section-link">
              Set up peer support &rarr;
            </NuxtLink>
          </DashedBox>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
const { memberData, checkMemberStatus } = useAuth();
const { isActive, statusConfig, isPendingPayment, canPeerSupport } = useMemberStatus();
const { completePayment, isProcessingPayment } = useMemberPayment();

const registeredEvents = ref([]);
const loadingEvents = ref(false);
const calendarLinkCopied = ref(false);
const showCalendarInstructions = ref(false);

// Calendar subscription URL
const calendarUrl = computed(() => {
  const memberId = memberData.value?._id || memberData.value?.id;
  if (!memberId) return "";
  const config = useRuntimeConfig();
  const baseUrl = config.public.appUrl || "http://localhost:3000";
  // Use webcal protocol for calendar subscription
  const webcalUrl = baseUrl.replace(/^https?:/, "webcal:");
  return `${webcalUrl}/api/members/my-calendar?memberId=${memberId}`;
});

// Copy calendar subscription link to clipboard
const copyCalendarLink = async () => {
  try {
    await navigator.clipboard.writeText(calendarUrl.value);
    calendarLinkCopied.value = true;
    showCalendarInstructions.value = true;
    setTimeout(() => {
      calendarLinkCopied.value = false;
    }, 2000);
  } catch (err) {
    console.error("Failed to copy calendar link:", err);
  }
};

const { openLoginModal } = useLoginModal();

// Handle authentication check on page load
const { pending: authPending } = await useLazyAsyncData(
  "dashboard-auth",
  async () => {
    // Only check authentication on client side
    if (process.server) return null;

    // If no member data, try to authenticate
    if (!memberData.value) {
      const isAuthenticated = await checkMemberStatus();

      if (!isAuthenticated) {
        // Show login modal instead of redirecting
        openLoginModal({
          title: "Sign in to your dashboard",
          description: "Enter your email to access your member dashboard",
          dismissible: true,
        });
        return null;
      }
    }

    return memberData.value;
  },
);

// Load registered events
const loadRegisteredEvents = async () => {
  const memberId = memberData.value?._id || memberData.value?.id;

  if (!memberId) {
    return;
  }

  loadingEvents.value = true;
  try {
    const response = await $fetch("/api/members/my-events", {
      params: { memberId },
    });
    registeredEvents.value = response.events;
  } catch (error) {
    console.error("Failed to load registered events:", error);
  } finally {
    loadingEvents.value = false;
  }
};

// Valid ghost avatar options
const validAvatars = [
  "disbelieving",
  "double-take",
  "exasperated",
  "mild",
  "sweet",
];

const isValidAvatar = (avatar) => {
  if (!avatar) return false;
  return validAvatars.includes(avatar.toLowerCase());
};

const capitalize = (str) => {
  if (!str) return "";
  // Handle kebab-case or multi-word avatars (e.g., "double-take" -> "Double-Take")
  return str
    .split("-")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join("-");
};

// Helper functions for event display
const getEventImageUrl = (featureImage) => {
  if (!featureImage) return "";

  if (featureImage.url) {
    return featureImage.url;
  }

  if (featureImage.publicId) {
    const config = useRuntimeConfig();
    return `https://res.cloudinary.com/${config.public.cloudinaryCloudName}/image/upload/w_200,h_200,c_fill,f_auto,q_auto/${featureImage.publicId}`;
  }

  return "";
};

const formatEventDate = (dateString) => {
  const date = new Date(dateString);
  return new Intl.DateTimeFormat("en-US", {
    month: "short",
    day: "numeric",
  }).format(date);
};

const formatEventTime = (dateString) => {
  const date = new Date(dateString);
  return new Intl.DateTimeFormat("en-US", {
    hour: "numeric",
    minute: "2-digit",
  }).format(date);
};

const formatMemberSince = (dateString) => {
  const date = new Date(dateString);
  return new Intl.DateTimeFormat("en-US", {
    month: "short",
    year: "numeric",
  }).format(date);
};

onMounted(() => {
  loadRegisteredEvents();
});

// Set page meta
useHead({
  title: "Member Dashboard - Ghost Guild",
});
</script>

<style scoped>
/* ---- DASHBOARD LAYOUT ---- */
.dashboard {
  max-width: 960px;
  margin: 0 auto;
}

/* ---- LOADING / UNAUTH STATES ---- */
.loading-state {
  text-align: center;
  padding: 80px 24px;
  color: var(--text-faint);
}

.spinner {
  width: 24px;
  height: 24px;
  border: 2px dashed var(--candle);
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 12px;
}

.spinner-sm {
  width: 16px;
  height: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-inline {
  padding: 24px 0;
  text-align: center;
}

.unauth-state {
  text-align: center;
  padding: 80px 24px;
  max-width: 400px;
  margin: 0 auto;
}

.unauth-state h2 {
  font-family: 'Brygada 1918', serif;
  font-size: 20px;
  font-weight: 500;
  color: var(--text-bright);
  margin-bottom: 8px;
}

.unauth-state p {
  color: var(--text-dim);
  font-size: 12px;
  margin-bottom: 20px;
}

/* ---- WELCOME HEADER ---- */
.welcome {
  padding: 28px 28px;
  border-bottom: 1px dashed var(--border);
  display: flex;
  align-items: baseline;
  gap: 16px;
  flex-wrap: wrap;
}

.welcome h1 {
  font-family: 'Brygada 1918', serif;
  font-size: 24px;
  font-weight: 500;
  color: var(--text-bright);
  line-height: 1.2;
}

.welcome .meta {
  display: flex;
  align-items: baseline;
  gap: 12px;
  font-size: 12px;
  color: var(--text-dim);
}

/* ---- CONTENT GRID ---- */
.content-row {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  border-bottom: 1px dashed var(--border);
}

.content-block {
  padding: 24px 28px;
  border-right: 1px dashed var(--border);
  min-width: 0;
  overflow-wrap: break-word;
}

.content-block:last-child {
  border-right: none;
}

/* ---- EVENT LIST ---- */
.event-list {
  margin-bottom: 4px;
}

.event-item {
  display: grid;
  grid-template-columns: 64px 1fr auto;
  gap: 12px;
  align-items: baseline;
  padding: 10px 0;
  border-bottom: 1px dashed var(--border);
  transition: padding-left 0.2s;
  text-decoration: none;
  color: inherit;
}

.event-item:last-of-type {
  border-bottom: none;
}

.event-item:hover {
  padding-left: 4px;
  text-decoration: none;
}

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

.event-title {
  color: var(--text);
  font-size: 13px;
}

.event-item:hover .event-title {
  color: var(--candle);
}

/* ---- CALENDAR BUTTON ---- */
.calendar-btn {
  font-family: 'Commit Mono', monospace;
  font-size: 11px;
  color: var(--candle-dim);
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px 0 0;
}

.calendar-btn:hover {
  color: var(--candle);
}

/* ---- CALENDAR INSTRUCTIONS ---- */
.calendar-instructions {
  margin-top: 16px;
  padding: 16px 20px;
  border: 1px dashed var(--border);
  font-size: 12px;
}

.ci-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
  color: var(--text-bright);
  font-size: 12px;
}

.ci-close {
  background: none;
  border: none;
  color: var(--text-faint);
  cursor: pointer;
  font-size: 16px;
  line-height: 1;
  padding: 0;
}

.ci-close:hover {
  color: var(--text);
}

.calendar-instructions ul {
  list-style: disc;
  padding-left: 16px;
  color: var(--text-dim);
  font-size: 11px;
  line-height: 1.8;
}

.ci-note {
  font-size: 11px;
  color: var(--text-faint);
  margin-top: 8px;
}

/* ---- EMPTY STATE ---- */
.empty-state {
  padding: 16px 0;
}

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

/* ---- SECTION LINK ---- */
.section-link {
  display: inline-block;
  margin-top: 16px;
  font-size: 12px;
  color: var(--candle);
  text-decoration: none;
}

.section-link:hover {
  text-decoration: underline;
}

/* ---- QUICK ACTIONS ---- */
.quick-action {
  border: 1px dashed var(--border);
  padding: 14px 20px;
  margin-bottom: 8px;
  transition: border-color 0.2s;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: var(--text);
  font-size: 13px;
  text-decoration: none;
}

.quick-action:hover {
  border-color: var(--candle-faint);
  color: var(--candle);
  text-decoration: none;
}

.quick-action.disabled {
  opacity: 0.4;
  pointer-events: none;
  cursor: not-allowed;
}

.quick-action .arrow {
  color: var(--text-faint);
  margin-left: 8px;
  transition: color 0.2s;
}

.quick-action:hover .arrow {
  color: var(--candle-faint);
}

/* ---- MEMBERSHIP SUMMARY ---- */
.membership-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px dashed var(--border);
  font-size: 12px;
}

.membership-row:last-of-type {
  border-bottom: none;
}

.membership-row .key {
  color: var(--text-faint);
}

.membership-row .val {
  color: var(--text);
  text-transform: capitalize;
}

.status-active {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.status-active::before {
  content: '';
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--green);
}

/* ---- PEER SUPPORT ---- */
.peer-text {
  color: var(--text-dim);
  font-size: 12px;
  line-height: 1.65;
}

/* ---- RESPONSIVE ---- */
@media (max-width: 768px) {
  .content-row {
    grid-template-columns: 1fr;
  }

  .content-block {
    border-right: none;
    border-bottom: 1px dashed var(--border);
  }

  .content-block:last-child {
    border-bottom: none;
  }

  .welcome {
    padding: 24px 20px;
  }

  .content-block {
    padding: 20px;
  }

  .event-item {
    grid-template-columns: 56px 1fr auto;
    gap: 8px;
  }
}
</style>
