
<template>
  <div v-if="displayPrices.length > 0" class="w-full mb-8 mt-6 animate-fade-in">
    <!-- Title -->
    

    <!-- Main Consolidated Box -->
    <div class="card-glass relative h-28 flex items-center px-6 overflow-x-auto no-scrollbar">
      
      <!-- Horizontal Price Line Container -->
      <div class="flex items-center justify-between w-full min-w-max md:min-w-0 relative gap-2 h-full">
        
        <template v-for="(price, index) in displayPrices" :key="price.company_name">
          
          <!-- CASE 1: Our Price Indicator (Highlighted Bubble) -->
          <div v-if="price.isOurPrice" class="flex flex-col items-center px-3 py-2 rounded-xl bg-info/5 border border-info/20 shadow-sm transition-all duration-300 group self-center z-10 mx-2">
             <!-- Price -->
             <div class="mb-0 pointer-events-none">
                <span class="font-mono font-black text-lg tracking-tight text-info">
                  ${{ Number(price.price_decimal).toFixed(3) }}
                </span>
             </div>
             
             <!-- Label -->
             <span class="text-[9px] uppercase font-black tracking-wider text-info whitespace-nowrap mt-0.5">
               Our Price
             </span>
          </div>

          <!-- CASE 2: Competitor Price -->
          <div v-else class="flex flex-col items-center px-4 py-2 rounded-lg hover:bg-base-content/5 transition-all duration-300 group self-center z-0">
             <!-- Price Bubble -->
             <div class="mb-1 pointer-events-none group-hover:-translate-y-1 transition-transform duration-300">
                <span class="font-mono font-bold text-lg tracking-tight" :class="getTextColor(Number(price.price_decimal))">
                  ${{ Number(price.price_decimal).toFixed(3) }}
                </span>
             </div>
             
             <!-- Color Dot Indicator -->
             <div class="w-1.5 h-1.5 rounded-full mb-2 opacity-50" :class="getStatusColor(Number(price.price_decimal))"></div>

             <!-- Company Name -->
             <span class="text-[10px] uppercase font-bold tracking-wider opacity-60 group-hover:opacity-100 transition-opacity whitespace-nowrap max-w-[100px] truncate">
               {{ formatCompanyName(price.company_name) }}
             </span>
          </div>
          
          <!-- Connector Line -->
           <div v-if="index < displayPrices.length - 1 && !displayPrices[index+1].isOurPrice && !price.isOurPrice" class="h-px w-8 bg-base-content/10 mx-2 self-center"></div>

        </template>
        
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import { PriceRecord } from '../services/scraperService';
import { queryService } from '../services/queryService';

const props = defineProps<{
  prices: PriceRecord[];
}>();

const ourPrice = ref<number | null>(null);

onMounted(async () => {
  try {
    const response = await queryService.getOilPrice();
    const data = response.data as any;
    if (data.ok && data.price_for_customer) {
      ourPrice.value = data.price_for_customer;
    }
  } catch (e) {
    console.error('Failed to fetch our oil price', e);
  }
});

const TARGET_COMPANIES = [
  'CHARLTON OIL',
  'LMT OIL',
  'LEBLANC OIL',
  'ALS OIL',
  'VALUE OIL',
  'DADDY\'S OIL'
];

interface DisplayPrice extends PriceRecord {
  isOurPrice?: boolean;
}

const normalize = (name: string) => name.toUpperCase().replace(/[^A-Z0-9]/g, '');

const filteredPrices = computed(() => {
  const targets = TARGET_COMPANIES.map(normalize);
  return props.prices.filter(p => {
    const nName = normalize(p.company_name);
    return targets.some(t => nName.includes(t));
  });
});

const displayPrices = computed(() => {
  let list: DisplayPrice[] = [...filteredPrices.value];

  if (ourPrice.value !== null) {
    list.push({
      company_name: 'OUR PRICE',
      town: 'Auburn',
      price_decimal: ourPrice.value,
      scrape_date: new Date().toISOString(),
      zone: 'internal',
      isOurPrice: true
    });
  }

  // Sort lowest to highest
  return list.sort((a, b) => a.price_decimal - b.price_decimal);
});

const averagePrice = computed(() => {
  if (filteredPrices.value.length === 0) return 0;
  const sum = filteredPrices.value.reduce((acc, curr) => acc + curr.price_decimal, 0);
  return sum / filteredPrices.value.length;
});

const getTextColor = (price: number) => {
  if (price < averagePrice.value - 0.05) return 'text-success';
  if (price > averagePrice.value + 0.05) return 'text-warning';
  return 'text-base-content';
};

const getStatusColor = (price: number) => {
  if (price < averagePrice.value - 0.05) return 'bg-success';
  if (price > averagePrice.value + 0.05) return 'bg-warning';
  return 'bg-base-content/30';
};

const formatCompanyName = (name: string) => {
  if (name === 'OUR PRICE') return 'OUR PRICE';
  return name.replace(/ OIL$/i, '').trim();
};
</script>

<style scoped>
.card-glass {
  @apply bg-base-100/80 backdrop-blur-md border border-base-content/10 shadow-lg rounded-2xl;
}

.no-scrollbar::-webkit-scrollbar {
  display: none;
}
.no-scrollbar {
  -ms-overflow-style: none;
  scrollbar-width: none;
}
</style>
