<template>
  <div>
    <!-- Unauthenticated -->
    <div v-if="!memberData" class="loading">
      <p>Please sign in to access your account settings.</p>
      <button class="btn btn-primary" @click="openLoginModal({ title: 'Sign in to manage your account' })">Sign In</button>
    </div>

    <div v-else>
      <!-- PAGE HEADER -->
      <PageHeader title="Account Settings" subtitle="Manage your membership and billing" />

      <!-- CONTENT AREA WITH EVENTS SIDEBAR -->
      <div class="content-area">
        <div class="page-content">
          <div class="account-columns">

            <!-- LEFT COLUMN: Membership Status & Email -->
            <div class="account-col-left">
              <div class="section-label">Current Membership</div>

              <div class="membership-card">
                <table>
                  <tr>
                    <td>Status</td>
                    <td>
                      <span class="status-dot" :class="memberData.status || 'active'"></span>
                      {{ memberData.status || 'Active' }}
                    </td>
                  </tr>
                  <tr>
                    <td>Circle</td>
                    <td :style="{ color: `var(--c-${memberData.circle || 'community'})` }">
                      {{ memberData.circle || 'Community' }}
                    </td>
                  </tr>
                  <tr>
                    <td>Contribution</td>
                    <td>${{ memberData.contributionAmount || 0 }} / month</td>
                  </tr>
                  <tr>
                    <td>Member since</td>
                    <td>{{ formatMemberSince(memberData.createdAt) }}</td>
                  </tr>
                </table>
              </div>

              <!-- Email -->
              <hr class="section-divider">
              <div class="section-label">Email</div>
              <div class="email-display">
                <span class="email-value">{{ memberData.email }}</span>
              </div>
              <div class="email-hint">Used for login magic links and notifications</div>

              <!-- Danger Zone -->
              <hr class="section-divider danger">
              <div class="section-label danger">Danger Zone</div>
              <div class="danger-zone">
                <p>Cancelling your membership will immediately revoke access to member-only resources, events, and the Slack workspace. <strong>This action cannot be easily undone.</strong></p>
                <button class="btn btn-danger" @click="handleCancelMembership" :disabled="isCancelling">
                  {{ isCancelling ? 'Cancelling...' : 'Cancel Membership' }}
                </button>
              </div>
            </div>

            <!-- RIGHT COLUMN: Change Contribution & Circle -->
            <div class="account-col-right">
              <div class="section-label">Change Contribution</div>

              <TierPicker v-model="selectedTier" :tiers="tiers" />
              <div class="tier-hint">Changes take effect on your next billing cycle</div>
              <button
                class="btn btn-primary btn-section"
                @click="handleUpdateTier"
                :disabled="selectedTier === memberData.contributionAmount || isUpdating"
              >
                {{ isUpdating ? 'Updating...' : 'Update Contribution' }}
              </button>

              <!-- Change Circle -->
              <hr class="section-divider">
              <div class="section-label">Change Circle</div>

              <CirclePicker v-model="selectedCircle" :circles="circleOptions" />
              <button
                class="btn btn-primary btn-section"
                @click="handleUpdateCircle"
                :disabled="selectedCircle === memberData.circle || isUpdating"
              >
                {{ isUpdating ? 'Updating...' : 'Update Circle' }}
              </button>
            </div>
          </div>
        </div>

        <!-- EVENTS MINI SIDEBAR -->
        <EventsMiniSidebar :events="upcomingEvents" />
      </div>
    </div>
  </div>
</template>

<script setup>
definePageMeta({
  middleware: 'auth',
})

const { memberData, checkMemberStatus } = useAuth()
const { openLoginModal } = useLoginModal()
const toast = useToast()

const selectedTier = ref(0)
const selectedCircle = ref('')
const isUpdating = ref(false)
const isCancelling = ref(false)

const tiers = [
  { amount: 0, display: '$0', label: 'Solidarity' },
  { amount: 5, display: '$5', label: 'Supporter' },
  { amount: 15, display: '$15', label: 'Sustainer' },
  { amount: 30, display: '$30', label: 'Builder' },
  { amount: 50, display: '$50', label: 'Champion' },
]

const circleOptions = [
  { value: 'community', label: 'Community', description: 'For anyone interested in cooperative game dev. Access discussions, events, and resources.' },
  { value: 'founder', label: 'Founder', description: 'For those actively building or running a cooperative studio. Peer support and deep dives.' },
  { value: 'practitioner', label: 'Practitioner', description: 'For professionals advising co-ops: lawyers, accountants, facilitators, consultants.' },
]

// Initialize from member data
watchEffect(() => {
  if (memberData.value) {
    selectedTier.value = memberData.value.contributionAmount || 0
    selectedCircle.value = memberData.value.circle || 'community'
  }
})

const { data: upcomingEvents } = await useFetch('/api/events', {
  query: { limit: 3, upcoming: true },
  default: () => [],
})

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

const handleUpdateTier = async () => {
  isUpdating.value = true
  try {
    await $fetch('/api/members/update-contribution', {
      method: 'POST',
      body: { amount: selectedTier.value },
    })
    await checkMemberStatus()
    toast.add({ title: 'Contribution updated', color: 'green' })
  } catch (err) {
    toast.add({ title: 'Update failed', description: err.data?.statusMessage || 'Please try again.', color: 'red' })
  } finally {
    isUpdating.value = false
  }
}

const handleUpdateCircle = async () => {
  isUpdating.value = true
  try {
    await $fetch('/api/members/update-circle', {
      method: 'POST',
      body: { circle: selectedCircle.value },
    })
    await checkMemberStatus()
    toast.add({ title: 'Circle updated', color: 'green' })
  } catch (err) {
    toast.add({ title: 'Update failed', description: err.data?.statusMessage || 'Please try again.', color: 'red' })
  } finally {
    isUpdating.value = false
  }
}

const handleCancelMembership = async () => {
  isCancelling.value = true
  try {
    await $fetch('/api/members/cancel', { method: 'POST' })
    await checkMemberStatus()
    toast.add({ title: 'Membership cancelled', color: 'orange' })
  } catch (err) {
    toast.add({ title: 'Cancellation failed', description: err.data?.statusMessage || 'Please try again.', color: 'red' })
  } finally {
    isCancelling.value = false
  }
}
</script>

<style scoped>
.loading {
  padding: 48px 32px;
  color: var(--text-dim);
}

/* ---- CONTENT AREA ---- */
.content-area {
  display: grid;
  grid-template-columns: 1fr 200px;
}
.page-content {
  min-width: 0;
}

/* ---- TWO-COLUMN LAYOUT ---- */
.account-columns {
  display: grid;
  grid-template-columns: 1fr 1fr;
}
.account-col-left {
  padding: 24px 28px;
  border-right: 1px dashed var(--border);
}
.account-col-right {
  padding: 24px 28px;
}

/* ---- MEMBERSHIP CARD ---- */
.membership-card {
  border: 1px dashed var(--border);
  padding: 16px 20px;
  margin-bottom: 12px;
}
.membership-card table {
  width: 100%;
  border-collapse: collapse;
}
.membership-card td {
  padding: 4px 0;
  font-size: 12px;
  border-bottom: 1px dashed var(--border);
}
.membership-card tr:last-child td {
  border-bottom: none;
}
.membership-card td:first-child {
  color: var(--text-faint);
  width: 120px;
}
.membership-card td:last-child {
  color: var(--text);
}

.status-dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin-right: 4px;
  vertical-align: middle;
}
.status-dot.active { background: var(--green); }
.status-dot.suspended { background: var(--ember); }
.status-dot.cancelled { background: var(--text-faint); }
.status-dot.pending_payment { background: var(--candle); }

/* ---- EMAIL ---- */
.email-display {
  display: flex;
  align-items: baseline;
  gap: 12px;
  font-size: 13px;
}
.email-value {
  color: var(--text);
}
.email-hint {
  font-size: 11px;
  color: var(--text-faint);
  margin-top: 6px;
}

/* ---- DANGER ZONE ---- */
.section-divider.danger {
  border-color: var(--ember);
}
.section-label.danger {
  color: var(--ember);
}
.danger-zone p {
  font-size: 12px;
  color: var(--text-dim);
  line-height: 1.7;
  margin-bottom: 12px;
  max-width: 400px;
}

/* ---- TIER HINT ---- */
.tier-hint {
  font-size: 11px;
  color: var(--text-faint);
  margin-bottom: 12px;
}

.btn-section {
  width: 100%;
  text-align: center;
}

/* ---- RESPONSIVE ---- */
@media (max-width: 1024px) {
  .content-area { grid-template-columns: 1fr; }
  .account-columns { grid-template-columns: 1fr; }
  .account-col-left {
    border-right: none;
    border-bottom: 1px dashed var(--border);
  }
}
</style>
