"use client";

import { useQuery } from "@tanstack/react-query";
import { useRef } from "react";
import axios from "axios";
import { format } from "date-fns";

const TopNavbar = () => {
  const marqueeRef = useRef(null);

  // Fetch metal rates from API
  const { data: metalRates = [] } = useQuery({
    queryKey: ["metal-rates"],
    queryFn: async () => {
      const response = await axios.get("/api/metal-rates");
      return response.data.rows || [];
    },
    refetchInterval: 60000, // Refetch every minute
  });

  // Filter only active metal rates (status = 1)
  const activeRates = metalRates.filter((rate) => rate.status === 1);

  // Build parts conditionally from active metal rates
  const parts = activeRates.map((rate) => {
    const metalName = rate.metal_name;
    const purity = rate.purity ? ` ${rate.purity}` : "";
    const unit = rate.unit==="gram" ? "gm" : "ct";
    const price = parseFloat(rate.rate).toFixed(2);
    
    return `${metalName}${purity} (1${unit}) = ₹${price}`;
  });

  // Get the most recent update time from active rates
  const lastUpdated = activeRates.length > 0 
    ? activeRates.reduce((latest, rate) => {
        const rateTime = new Date(rate.updated_at);
        return rateTime > latest ? rateTime : latest;
      }, new Date(activeRates[0].updated_at))
    : null;

  const updateTimeText = lastUpdated 
    ? `Last updated: ${format(lastUpdated, "dd/MM/yyyy, hh:mm a")}`
    : "";

  // If no rates, show nothing
  if (parts.length === 0) return null;

  return (
    <div className="hidden md:block w-full bg-brand-gold text-brand-dark text-sm font-bold py-2 overflow-hidden px-6">
      <marquee
        ref={marqueeRef}
        behavior="scroll"
        direction="left"
        scrollamount="6"
        onMouseEnter={() => marqueeRef.current?.stop()}
        onMouseLeave={() => marqueeRef.current?.start()}
        className="whitespace-nowrap px-4"
      >
        {parts.join("   |   ")}
        {updateTimeText && `   |   ${updateTimeText}`}
      </marquee>
    </div>
  );
};

export default TopNavbar;

