
<template>
  <div v-if="loading" class="flex items-center space-x-4 max-w-full overflow-hidden whitespace-nowrap text-xs h-6">
    <span class="loading loading-dots loading-xs opacity-50"></span>
  </div>
  <div v-else class="ticker-container w-full overflow-hidden h-6 select-none flex items-center">
    <!-- Play/Pause Button -->
    <button 
      @click="isPaused = !isPaused" 
      class="btn btn-ghost btn-xs btn-circle z-20 bg-base-300/80 hover:bg-base-300 ml-1 shrink-0"
      :title="isPaused ? 'Play Ticker' : 'Pause Ticker'"
    >
      <svg v-if="isPaused" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-3 h-3">
        <path d="M6.3 2.841A.75.75 0 017.05 2.5a.75.75 0 01.35.087l8.25 5c.429.26.429.926 0 1.186l-8.25 5A.75.75 0 016.3 13.159V2.841z" />
      </svg>
      <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-3 h-3">
        <path d="M5.75 3a.75.75 0 00-.75.75v12.5c0 .414.336.75.75.75h1.5a.75.75 0 00.75-.75V3.75A.75.75 0 007.25 3h-1.5zM12.75 3a.75.75 0 00-.75.75v12.5c0 .414.336.75.75.75h1.5a.75.75 0 00.75-.75V3.75a.75.75 0 00-.75-.75h-1.5z" />
      </svg>
    </button>

    <div class="ticker-track flex items-center whitespace-nowrap text-xs font-mono" :class="{ 'is-paused-perma': isPaused }">
      <!-- Original List -->
      <div class="ticker-content flex items-center space-x-12 px-6">
        <div 
          v-for="item in tickerItems" 
          :key="'original-' + item.symbol" 
          class="flex items-center space-x-2 transition-opacity hover:opacity-80"
        >
          <span class="font-bold text-base-content/70">{{ getDisplayName(item.symbol) }}</span>
          <div class="flex items-center space-x-1">
            <span class="font-bold">{{ formatPrice(item.price) }}</span>
            <span 
              :class="getChangeColor(item.change)"
              class="flex items-center text-[10px]"
            >
              <span class="mr-0.5">{{ item.change >= 0 ? '▲' : '▼' }}</span>
              {{ Math.abs(item.percent_change).toFixed(2) }}%
            </span>
          </div>
        </div>
        
        <!-- Last Updated (Original) -->
        <div class="text-[10px] text-base-content/40 pl-4 border-l border-base-content/10">
          Last Updated: {{ lastUpdated }}
        </div>
      </div>

      <!-- Duplicated List for Seamless Loop -->
      <div class="ticker-content flex items-center space-x-12 px-6" aria-hidden="true">
        <div 
          v-for="item in tickerItems" 
          :key="'duplicate-' + item.symbol" 
          class="flex items-center space-x-2 transition-opacity"
        >
          <span class="font-bold text-base-content/70">{{ getDisplayName(item.symbol) }}</span>
          <div class="flex items-center space-x-1">
            <span class="font-bold">{{ formatPrice(item.price) }}</span>
            <span 
              :class="getChangeColor(item.change)"
              class="flex items-center text-[10px]"
            >
              <span class="mr-0.5">{{ item.change >= 0 ? '▲' : '▼' }}</span>
              {{ Math.abs(item.percent_change).toFixed(2) }}%
            </span>
          </div>
        </div>
        
        <!-- Last Updated (Duplicate) -->
        <div class="text-[10px] text-base-content/40 pl-4 border-l border-base-content/10">
          Last Updated: {{ lastUpdated }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import axios from 'axios';
import authHeader from '../services/auth.header';

interface TickerItem {
  symbol: string;
  price: number;
  currency: string;
  change: number;
  percent_change: number;
  timestamp: string;
}

const loading = ref(true);
const isPaused = ref(false); // New persistence state
const tickerItems = ref<TickerItem[]>([]);
const lastUpdated = ref<string>('');
let intervalId: number | null = null;

const getDisplayName = (symbol: string) => {
  switch (symbol) {
    case 'HO=F': return 'HEATING OIL';
    case 'CL=F': return 'CRUDE OIL';
    case 'RB=F': return 'GASOLINE';
    case 'LMT OIL': return 'LMT';
    case 'CHARLTON OIL': return 'CHARLTON';
    case 'LEBLANC OIL': return 'LEBLANC';
    case 'ALS OIL': return 'AL\'S';
    case 'VALUE OIL': return 'VALUE';
    case 'DADDY\'S OIL': return 'DADDY\'S';
    default: return symbol;
  }
};

const formatPrice = (price: number) => {
  return price.toFixed(4);
};

const getChangeColor = (change: number) => {
  if (change > 0) return 'text-success';
  if (change < 0) return 'text-error';
  return 'text-base-content/50';
};

const fetchTickerData = async () => {
  try {
    const path = import.meta.env.VITE_BASE_URL + '/info/price/ticker';
    const response = await axios.get(path, {
      headers: authHeader(),
      withCredentials: true
    });
    
    if (response.data.ok && response.data.tickers) {
      const data = response.data.tickers;
      const order = ['CL=F', 'HO=F', 'RB=F', 'LMT', 'CHARLTON', 'LEBLANC', 'ALS', 'VALUE', 'DADDY'];
      
      tickerItems.value = order
        .map(key => data[key])
        .filter(item => item !== undefined);
        
      lastUpdated.value = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }
  } catch (error) {
    console.error('Failed to fetch ticker data:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchTickerData();
  // Refresh every 1 minute
  intervalId = window.setInterval(fetchTickerData, 1 * 60 * 1000);
});

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId);
  }
});
</script>

<style scoped>
.ticker-container {
  display: flex;
  align-items: center;
}

.ticker-track {
  display: flex;
  width: max-content;
  animation: scroll-ticker 30s linear infinite;
  will-change: transform;
}

.ticker-container:hover .ticker-track,
.ticker-track.is-paused-perma {
  animation-play-state: paused;
}

@keyframes scroll-ticker {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-50%);
  }
}

.ticker-content {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}
</style>
