<template>
  <PageShell>
    <ClientOnly>
      <!-- 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>
        <OnboardingWidget />

        <ColumnsLayout cols="events-sidebar" :limit="5">
          <!-- Member Status Banner -->
          <MemberStatusBanner />

          <!-- Welcome Header -->
          <PageHeader :title="welcomeTitle">
            <div class="dashboard-meta">
              <CircleBadge :circle="memberData?.circle || 'community'" />
              <span>${{ memberData?.contributionAmount ?? 0 }} CAD/mo</span>
            </div>
          </PageHeader>

          <!-- 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
                    type="button"
                    class="ci-close"
                    @click="showCalendarInstructions = false"
                  >
                    &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="/board"
                class="quick-action"
                :class="{ disabled: !canPeerSupport }"
                :title="
                  !canPeerSupport
                    ? 'Complete your membership to access the board'
                    : ''
                "
              >
                Board<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"
                @click="handleWikiClick"
              >
                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/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?.contributionAmount ?? 0 }} 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/account" class="section-link">
                Change circle or contribution &rarr;
              </NuxtLink>
            </div>

            <div class="content-block">
              <div class="section-label">Bulletin Board</div>
              <DashedBox>
                <p class="peer-text">
                  Make offers and requests related to shared interests and
                  cooperative topics.
                </p>
                <NuxtLink to="/board" class="section-link">
                  Browse the Bulletin Board &rarr;
                </NuxtLink>
              </DashedBox>
            </div>
          </div>
        </ColumnsLayout>
      </template>

      <template #fallback>
        <div class="loading-state">
          <div class="spinner" />
          <p>Loading your dashboard...</p>
        </div>
      </template>
    </ClientOnly>
  </PageShell>
</template>

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

const route = useRoute();
const isNewSignup = computed(() => route.query.welcome === "1");
const welcomeTitle = computed(() => {
  const name = memberData.value?.name || "";
  return isNewSignup.value
    ? `Welcome to Ghost Guild, ${name}`
    : `Welcome back, ${name}`;
});
const { completePayment, isProcessingPayment } = useMemberPayment();
const { trackGoal, isComplete: onboardingComplete } = useOnboarding();

const handleWikiClick = () => {
  if (!onboardingComplete.value) {
    trackGoal("wikiClicked");
  }
};

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
// server: false ensures this always runs on the client, even on a hard page load.
// The auth middleware only fires for client-side navigations in Nuxt 4, so we
// can't rely on it to open the modal when the user lands directly on this URL.
const { pending: authPending } = await useLazyAsyncData(
  "dashboard-auth",
  async () => {
    if (!memberData.value) {
      const isAuthenticated = await checkMemberStatus();

      if (!isAuthenticated) {
        openLoginModal({
          title: "Sign in to continue",
          description: "You need to be signed in to access this page",
          dismissible: true,
          redirectTo: "/member/dashboard",
        });
        return null;
      }
    }

    return memberData.value;
  },
  { server: false },
);

// 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>
/* ---- LOADING / UNAUTH STATES ---- */
.loading-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 48px 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 {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 48px 24px;
  max-width: 400px;
  width: 100%;
  margin: 0 auto;
  box-sizing: border-box;
}

.unauth-state h2 {
  font-family: var(--font-display);
  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 META ---- */
.dashboard-meta {
  display: flex;
  align-items: baseline;
  gap: 12px;
  font-size: 12px;
  color: var(--text-dim);
  margin-top: 8px;
}

.content-row {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  border-bottom: 1px dashed var(--border);
  align-items: stretch;
}

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

.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: inherit;
  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: 12px 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;
  }

  .content-block {
    padding: 20px 24px;
  }

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