<template>
  <div class="profile-page">
    <!-- Loading State -->
    <div v-if="pending" class="loading-state">
      <p>Loading profile...</p>
    </div>

    <!-- Error / 404 State -->
    <div v-else-if="fetchError || !member" class="error-state">
      <p class="error-title">Member not found</p>
      <p class="error-sub">This profile doesn't exist or isn't public.</p>
      <NuxtLink to="/members" class="btn">← Back to Members</NuxtLink>
    </div>

    <!-- Profile Content -->
    <div v-else class="profile-content">
      <!-- Header Area -->
      <div class="profile-header">
        <div class="profile-avatar">
          <img
            v-if="member.avatar"
            :src="`/ghosties/Ghost-${member.avatar.charAt(0).toUpperCase() + member.avatar.slice(1)}.png`"
            :alt="member.name"
            class="profile-avatar-img"
          />
          <span v-else class="profile-initials">{{
            getInitials(member.name)
          }}</span>
        </div>
        <div class="profile-identity">
          <h1 class="profile-name">
            {{ member.name }}
            <span v-if="member.pronouns" class="profile-pronouns">{{
              member.pronouns
            }}</span>
          </h1>
          <div class="profile-meta">
            <span v-if="member.circle" class="badge" :class="member.circle">{{
              circleLabels[member.circle]
            }}</span>
            <template v-if="member.studio">
              <span class="meta-sep">&middot;</span>
              <span class="profile-studio">{{ member.studio }}</span>
            </template>
          </div>
        </div>
      </div>

      <!-- Bio Section -->
      <div v-if="member.bio" class="profile-section">
        <div class="section-label">About</div>
        <div class="profile-bio" v-html="renderMarkdown(member.bio)"></div>
      </div>

      <!-- Location & Timezone -->
      <div v-if="member.location || member.timeZone" class="profile-section">
        <div class="section-label">Location</div>
        <p class="profile-detail">
          {{ [member.location, member.timeZone].filter(Boolean).join(" · ") }}
        </p>
      </div>

      <!-- What I Do (craft tags, falling back to offering) -->
      <div v-if="craftTagsDisplay.length > 0 || member.offering?.text" class="profile-section">
        <div class="section-label">What I Do</div>
        <div v-if="craftTagsDisplay.length > 0" class="tag-list">
          <span
            v-for="tag in craftTagsDisplay"
            :key="tag"
            class="tag-pill"
            >{{ tagLabel('craft', tag) }}</span
          >
        </div>
        <p v-if="member.offering?.text" class="profile-detail offering-text">
          {{ member.offering.text }}
        </p>
      </div>

      <!-- Community Connections (cooperative topics with states, falling back to lookingFor) -->
      <div
        v-if="connectionTopicsDisplay.length > 0 || member.lookingFor?.text || member.communityConnections?.details"
        class="profile-section"
      >
        <div class="section-label">Community Connections</div>
        <div v-if="connectionTopicsDisplay.length > 0" class="tag-list">
          <span
            v-for="topic in connectionTopicsDisplay"
            :key="topic.tagSlug || topic"
            class="tag-pill connection-pill"
          >
            <span v-if="topic.state" class="connection-state">{{ stateLabel(topic.state) }}</span>
            {{ tagLabel('cooperative', topic.tagSlug || topic) }}
          </span>
        </div>
        <p v-if="member.communityConnections?.details" class="profile-detail connection-details">
          {{ member.communityConnections.details }}
        </p>
        <p v-else-if="member.lookingFor?.text" class="profile-detail looking-text">
          {{ member.lookingFor.text }}
        </p>
      </div>

      <!-- Social Links -->
      <div
        v-if="
          member.socialLinks && Object.values(member.socialLinks).some(Boolean)
        "
        class="profile-section"
      >
        <div class="section-label">Links</div>
        <div class="social-links">
          <a
            v-if="member.socialLinks.website"
            :href="member.socialLinks.website"
            target="_blank"
            rel="noopener noreferrer"
            class="social-link"
            >Website</a
          >
          <a
            v-if="member.socialLinks.itch"
            :href="member.socialLinks.itch"
            target="_blank"
            rel="noopener noreferrer"
            class="social-link"
            >itch.io</a
          >
          <a
            v-if="member.socialLinks.mastodon"
            :href="member.socialLinks.mastodon"
            target="_blank"
            rel="noopener noreferrer"
            class="social-link"
            >Mastodon</a
          >
          <a
            v-if="member.socialLinks.bluesky"
            :href="member.socialLinks.bluesky"
            target="_blank"
            rel="noopener noreferrer"
            class="social-link"
            >Bluesky</a
          >
          <a
            v-if="member.socialLinks.linkedin"
            :href="member.socialLinks.linkedin"
            target="_blank"
            rel="noopener noreferrer"
            class="social-link"
            >LinkedIn</a
          >
        </div>
      </div>

      <!-- Peer Support Section (reads from communityConnections, falls back to peerSupport) -->
      <div v-if="showPeerSupport" class="profile-section">
        <div class="section-label">Peer Support</div>
        <div v-if="member.peerSupport?.skillTopics?.length" class="peer-group">
          <span class="peer-label">Skills:</span>
          <div class="tag-list">
            <span
              v-for="topic in member.peerSupport.skillTopics"
              :key="topic"
              class="tag-pill"
              >{{ topic }}</span
            >
          </div>
        </div>
        <div v-if="member.peerSupport?.supportTopics?.length" class="peer-group">
          <span class="peer-label">Topics:</span>
          <div class="tag-list">
            <span
              v-for="topic in member.peerSupport.supportTopics"
              :key="topic"
              class="tag-pill"
              >{{ topic }}</span
            >
          </div>
        </div>
        <p v-if="peerAvailability" class="profile-detail">
          {{ peerAvailability }}
        </p>
      </div>

      <!-- Recent Activity -->
      <div v-if="activityEntries.length" class="profile-section">
        <div class="section-label">Recent Activity</div>
        <div class="activity-list">
          <div v-for="entry in activityEntries" :key="entry._id" class="activity-item">
            <UIcon :name="getActivity(entry).icon" class="activity-icon" />
            <span class="activity-text">{{ getActivity(entry).text }}</span>
            <span class="activity-time">{{ formatRelativeDate(entry.timestamp) }}</span>
          </div>
        </div>
      </div>

      <!-- Auth Notice -->
      <div v-if="!isAuthenticated" class="auth-notice">
        <p>Sign in to see full profile details</p>
        <button
          type="button"
          class="btn"
          @click="
            openLoginModal({
              title: 'Sign in to see more',
              description: 'Log in to view full member profiles',
            })
          "
        >
          Log In
        </button>
      </div>

      <!-- Back Link -->
      <div class="profile-back">
        <NuxtLink to="/members" class="back-link">← Back to Members</NuxtLink>
      </div>
    </div>
  </div>
</template>

<script setup>
import { formatActivity } from '~/utils/activityText'

const route = useRoute();
const { isAuthenticated } = useAuth();
const { openLoginModal } = useLoginModal();
const { render: renderMarkdown } = useMarkdown();

const id = route.params.id;

const circleLabels = {
  community: "Community",
  founder: "Founder",
  practitioner: "Practitioner",
};

// State display text mapping
const stateLabels = {
  help: "Can help",
  interested: "Interested",
  seeking: "Need help",
};

const stateLabel = (state) => stateLabels[state] || state || "";

const getInitials = (name) => {
  if (!name) return "?";
  return name
    .split(" ")
    .map((w) => w[0])
    .join("")
    .toUpperCase()
    .slice(0, 2);
};

// Fetch member data — no await so the component renders immediately (no Suspense)
const { data, pending, error: fetchError } = useFetch(`/api/members/${id}`);

// Fetch tags for slug-to-label lookup
const { data: tagsData } = useFetch("/api/tags", {
  default: () => ({ tags: [] }),
});

// Fetch public activity
const { data: activityData } = useFetch(`/api/members/${id}/activity`, {
  params: { limit: 5 },
  default: () => ({ entries: [] })
})
const activityEntries = computed(() => activityData.value?.entries || [])

const getActivity = (entry) => formatActivity(entry)

const formatRelativeDate = (date) => {
  const now = new Date()
  const d = new Date(date)
  const diffInSeconds = Math.floor((now - d) / 1000)
  if (diffInSeconds < 60) return 'just now'
  if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}m ago`
  if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}h ago`
  if (diffInSeconds < 604800) return `${Math.floor(diffInSeconds / 86400)}d ago`
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
}
const member = computed(() => data.value?.member || null);

// Tag label lookup
const tagLabel = (pool, slug) => {
  const tags = tagsData.value?.tags || [];
  const found = tags.find((t) => t.slug === slug && t.pool === pool);
  return found ? found.label : slug;
};

// Craft tags display: new field, falling back to offering.tags
const craftTagsDisplay = computed(() => {
  if (!member.value) return [];
  if (member.value.craftTags && member.value.craftTags.length > 0) {
    return member.value.craftTags;
  }
  return member.value.offering?.tags || [];
});

// Connection topics display: new field, falling back to lookingFor.tags
const connectionTopicsDisplay = computed(() => {
  if (!member.value) return [];
  if (
    member.value.communityConnections?.topics &&
    member.value.communityConnections.topics.length > 0
  ) {
    return member.value.communityConnections.topics;
  }
  if (member.value.lookingFor?.tags && member.value.lookingFor.tags.length > 0) {
    return member.value.lookingFor.tags.map((tag) => ({ tagSlug: tag, state: null }));
  }
  return [];
});

// Peer support: check both new communityConnections and old peerSupport
const showPeerSupport = computed(() => {
  if (!member.value) return false;
  return (
    member.value.communityConnections?.offerPeerSupport ||
    member.value.peerSupport?.enabled
  );
});

// Peer availability: prefer new field, fall back to old
const peerAvailability = computed(() => {
  if (!member.value) return "";
  return (
    member.value.communityConnections?.availability ||
    member.value.peerSupport?.availability ||
    ""
  );
});

const pageBreadcrumbTitle = useState("pageBreadcrumbTitle", () => "");
watch(
  member,
  (val) => {
    pageBreadcrumbTitle.value = val?.name || "";
  },
  { immediate: true },
);
onUnmounted(() => {
  pageBreadcrumbTitle.value = "";
});

// Page head
useHead({
  title: computed(() =>
    member.value
      ? `${member.value.name} — Ghost Guild`
      : "Member Profile — Ghost Guild",
  ),
});
</script>

<style scoped>
.profile-page {
  max-width: 720px;
  margin: 0 auto;
  padding: 0 24px 60px;
}

/* ---- LOADING ---- */
.loading-state {
  padding: 80px 24px;
  text-align: center;
  color: var(--text-faint);
  font-size: 12px;
  font-family: "Commit Mono", monospace;
}

/* ---- ERROR / 404 ---- */
.error-state {
  padding: 80px 24px;
  text-align: center;
}

.error-title {
  font-family: "Brygada 1918", serif;
  font-size: 20px;
  color: var(--text-dim);
  margin-bottom: 6px;
}

.error-sub {
  font-size: 12px;
  color: var(--text-faint);
  margin-bottom: 20px;
}

/* ---- HEADER ---- */
.profile-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 28px 0 24px;
  border-bottom: 1px dashed var(--border);
}

.profile-avatar {
  width: 48px;
  height: 48px;
  background: var(--surface);
  border: 1px dashed var(--border);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  overflow: hidden;
}

.profile-avatar-img {
  width: 42px;
  height: 42px;
  object-fit: contain;
}

.profile-initials {
  font-family: "Commit Mono", monospace;
  font-size: 14px;
  color: var(--text-faint);
  font-weight: 600;
}

.profile-identity {
  min-width: 0;
}

.profile-name {
  font-family: "Brygada 1918", serif;
  font-size: 22px;
  font-weight: 600;
  color: var(--text-bright);
  margin: 0;
  line-height: 1.3;
}

.profile-pronouns {
  font-family: "Commit Mono", monospace;
  font-size: 12px;
  color: var(--text-faint);
  font-weight: 400;
  margin-left: 8px;
}

.profile-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 4px;
  font-size: 12px;
  color: var(--text-dim);
}

.meta-sep {
  color: var(--border);
}

.profile-studio {
  font-family: "Commit Mono", monospace;
}

/* ---- SECTIONS ---- */
.profile-section {
  padding: 20px 0;
  border-bottom: 1px dashed var(--border);
}

.section-label {
  font-family: "Commit Mono", monospace;
  font-size: 10px;
  text-transform: uppercase;
  letter-spacing: 0.08em;
  color: var(--text-faint);
  margin-bottom: 10px;
}

.profile-bio {
  font-size: 13px;
  color: var(--text-dim);
  line-height: 1.7;
}

.profile-bio :deep(p) {
  margin: 0 0 8px;
}

.profile-bio :deep(p:last-child) {
  margin-bottom: 0;
}

.profile-bio :deep(a) {
  color: var(--candle);
  text-decoration: underline;
}

.profile-bio :deep(a:hover) {
  color: var(--ember);
}

.profile-detail {
  font-size: 13px;
  color: var(--text-dim);
  line-height: 1.6;
  margin: 0;
}

.offering-text,
.looking-text,
.connection-details {
  margin-top: 8px;
}

/* ---- TAGS ---- */
.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.tag-pill {
  font-family: "Commit Mono", monospace;
  font-size: 10px;
  color: var(--text-dim);
  padding: 2px 8px;
  border: 1px dashed var(--border);
  white-space: nowrap;
}

.connection-pill {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.connection-state {
  font-size: 9px;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: var(--text-faint);
}

/* ---- SOCIAL LINKS ---- */
.social-links {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.social-link {
  font-family: "Commit Mono", monospace;
  font-size: 11px;
  color: var(--candle);
  text-decoration: none;
  padding: 3px 10px;
  border: 1px dashed var(--border);
  transition: all 0.15s;
}

.social-link:hover {
  border-color: var(--candle);
  color: var(--text-bright);
}

/* ---- PEER SUPPORT ---- */
.peer-group {
  margin-bottom: 10px;
}

.peer-group:last-child {
  margin-bottom: 0;
}

.peer-label {
  font-family: "Commit Mono", monospace;
  font-size: 11px;
  color: var(--text-faint);
  display: block;
  margin-bottom: 6px;
}

/* ---- ACTIVITY ---- */
.activity-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.activity-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.activity-icon {
  width: 14px;
  height: 14px;
  color: var(--text-faint);
  flex-shrink: 0;
}

.activity-text {
  color: var(--text-dim);
  flex: 1;
  min-width: 0;
}

.activity-time {
  color: var(--text-faint);
  font-size: 11px;
  flex-shrink: 0;
}

/* ---- AUTH NOTICE ---- */
.auth-notice {
  padding: 20px;
  margin-top: 24px;
  border: 1px dashed var(--candle-faint, var(--border));
  text-align: center;
}

.auth-notice p {
  font-size: 12px;
  color: var(--text-dim);
  margin: 0 0 12px;
}

/* ---- BACK LINK ---- */
.profile-back {
  padding: 24px 0;
}

.back-link {
  font-family: "Commit Mono", monospace;
  font-size: 12px;
  color: var(--text-faint);
  text-decoration: none;
  transition: color 0.15s;
}

.back-link:hover {
  color: var(--candle);
}

/* ---- RESPONSIVE ---- */
@media (max-width: 768px) {
  .profile-page {
    padding: 0 16px 40px;
  }

  .profile-header {
    padding: 20px 0 18px;
    gap: 12px;
  }

  .profile-name {
    font-size: 18px;
  }

  .profile-pronouns {
    display: block;
    margin-left: 0;
    margin-top: 2px;
  }

  .profile-section {
    padding: 16px 0;
  }
}
</style>
