<template>
  <div class="protocol-stats-card">
    <FCard>
      <template v-if="!initialized">
        <div class="stats-loading">
          <FLoader></FLoader>
          <p>Loading protocol statistics...</p>
        </div>
      </template>

      <template v-else-if="statsError">
        <div class="stats-error">
          <p>⚠️ Protocol statistics unavailable</p>
          <p class="error-detail">{{ statsError }}</p>
        </div>
      </template>

      <template v-else>
        <div class="stats-header">
          <h3 class="stats-title">
            Protocol Activity (last 24h)
            <IconInfo size="20px">
              <template #text>
                Real-time protocol health metrics from the Ponder indexer. Shows supply growth, tax collection, rebalance activity, and
                reserve status.
              </template>
            </IconInfo>
          </h3>
        </div>

        <div class="stats-grid">
          <div class="stats-row">
            <div class="stat-item">
              <span class="stat-label">Supply Growth:</span>
              <span class="stat-value" :class="{ positive: supplyGrowthPercent > 0, negative: supplyGrowthPercent < 0 }">
                {{ formatPercent(supplyGrowthPercent) }}
              </span>
            </div>
            <span class="stat-separator">·</span>
            <div class="stat-item">
              <span class="stat-label">Tax Collected:</span>
              <span class="stat-value">{{ formatToken(taxPaidLastDay) }} KRK</span>
            </div>
            <span class="stat-separator">·</span>
            <div class="stat-item">
              <span class="stat-label">Net Expansion:</span>
              <span class="stat-value" :class="{ positive: netExpansionRate > 0, negative: netExpansionRate < 0 }">
                {{ formatPercent(netExpansionRate) }}
              </span>
            </div>
          </div>

          <div class="stats-row">
            <div class="stat-item">
              <span class="stat-label">ETH Reserve:</span>
              <span class="stat-value">{{ formatToken(ethReserve) }} ETH</span>
            </div>
            <span class="stat-separator">·</span>
            <div class="stat-item">
              <span class="stat-label">Holders:</span>
              <span class="stat-value">{{ holderCount.toLocaleString() }}</span>
            </div>
          </div>

          <div class="stats-row">
            <div class="stat-item">
              <span class="stat-label">Last Rebalance:</span>
              <span class="stat-value">{{ lastRebalanceText }}</span>
            </div>
            <span class="stat-separator">·</span>
            <div class="stat-item">
              <span class="stat-label">Rebalances Today:</span>
              <span class="stat-value">{{ recentersLastDay }}</span>
            </div>
          </div>

          <div class="stats-row indicative-rate">
            <div class="stat-item">
              <span class="stat-label">Indicative Annual Rate:</span>
              <span class="stat-value rate-value">~{{ formatPercent(annualizedRate) }}</span>
              <span class="stat-disclaimer">(based on 7d average — not a promise)</span>
              <span class="stat-disclaimer stat-disclaimer--detail">Staking multiplies your position when supply grows, not from fees.</span>
            </div>
          </div>
        </div>
      </template>
    </FCard>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import FCard from '@/components/fcomponents/FCard.vue';
import FLoader from '@/components/fcomponents/FLoader.vue';
import IconInfo from '@/components/icons/IconInfo.vue';
import { useProtocolStats } from '@/composables/useProtocolStats';
import { useWallet } from '@/composables/useWallet';
import { DEFAULT_CHAIN_ID } from '@/config';

const wallet = useWallet();
const initialChainId = wallet.account.chainId ?? DEFAULT_CHAIN_ID;

const {
  initialized,
  statsError,
  supplyGrowthPercent,
  netExpansionRate,
  ethReserve,
  taxPaidLastDay,
  holderCount,
  recentersLastDay,
  lastRecenterTimestamp,
  annualizedRate,
} = useProtocolStats(initialChainId);

function formatToken(value: number, decimals: number = 2): string {
  if (!Number.isFinite(value)) {
    return '0';
  }
  return value.toLocaleString('en-US', {
    minimumFractionDigits: 0,
    maximumFractionDigits: decimals,
  });
}

function formatPercent(value: number): string {
  if (!Number.isFinite(value)) {
    return '0%';
  }
  const sign = value > 0 ? '+' : '';
  return `${sign}${value.toFixed(2)}%`;
}

const lastRebalanceText = computed(() => {
  if (!lastRecenterTimestamp.value) {
    return 'N/A';
  }

  const now = Date.now();
  const timestampMs = lastRecenterTimestamp.value * 1000;
  const diffMs = now - timestampMs;

  const diffMinutes = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMinutes / 60);
  const diffDays = Math.floor(diffHours / 24);

  if (diffDays > 0) {
    return `${diffDays}d ago`;
  } else if (diffHours > 0) {
    return `${diffHours}h ago`;
  } else if (diffMinutes > 0) {
    return `${diffMinutes}m ago`;
  } else {
    return 'Just now';
  }
});
</script>

<style lang="sass" scoped>
.protocol-stats-card
  margin-bottom: 24px

  .f-card
    background: linear-gradient(135deg, rgba(117, 80, 174, 0.08) 0%, rgba(117, 80, 174, 0.03) 100%)
    border: 1px solid rgba(117, 80, 174, 0.2)

.stats-loading,
.stats-error
  display: flex
  flex-direction: column
  align-items: center
  justify-content: center
  padding: 24px
  gap: 12px
  text-align: center

  p
    margin: 0
    color: #9A9898

  .error-detail
    font-size: 13px
    color: #666

.stats-header
  margin-bottom: 16px

  .stats-title
    display: flex
    align-items: center
    gap: 8px
    margin: 0
    font-size: 20px
    font-weight: 600
    color: #FFFFFF

.stats-grid
  display: flex
  flex-direction: column
  gap: 12px

.stats-row
  display: flex
  flex-wrap: wrap
  align-items: center
  gap: 8px
  font-size: 15px

  &.indicative-rate
    margin-top: 8px
    padding-top: 12px
    border-top: 1px solid rgba(117, 80, 174, 0.2)

.stat-item
  display: flex
  align-items: center
  gap: 6px
  flex-wrap: wrap

.stat-label
  color: #9A9898
  font-weight: 500

.stat-value
  color: #FFFFFF
  font-weight: 600

  &.positive
    color: #4ADE80

  &.negative
    color: #F87171

  &.rate-value
    color: #7550AE
    font-size: 16px

.stat-separator
  color: #666
  font-weight: 300

.stat-disclaimer
  color: #9A9898
  font-size: 13px
  font-style: italic
  font-weight: 400

.stat-disclaimer--detail
  display: block
  margin-top: 4px

@media (max-width: 768px)
  .stats-row
    flex-direction: column
    align-items: flex-start
    gap: 8px

  .stat-separator
    display: none
</style>
