"use client";

/**
 * @file features/layout/components/market-indices.tsx
 * @description KOSPI/KOSDAQ 지수를 표시하는 UI 컴포넌트
 *
 * @description [주요 책임]
 * - `useMarketIndices` 훅을 사용하여 지수 데이터를 가져옴
 * - 30초마다 데이터를 자동으로 새로고침
 * - 로딩 상태일 때 스켈레톤 UI를 표시
 * - 각 지수 정보를 `MarketIndexItem` 컴포넌트로 렌더링
 */

import { useEffect } from "react";
import { useMarketIndices } from "@/features/layout/hooks/use-market-indices";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import type { DomesticMarketIndexResult } from "@/lib/kis/dashboard";

const MarketIndexItem = ({ index }: { index: DomesticMarketIndexResult }) => (
  <div className="flex items-center space-x-2">
    <span className="text-sm font-medium">{index.name}</span>
    <span
      className={cn("text-sm", {
        "text-red-500": index.change > 0,
        "text-blue-500": index.change < 0,
      })}
    >
      {index.price.toLocaleString(undefined, {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      })}
    </span>
    <span
      className={cn("text-xs", {
        "text-red-500": index.change > 0,
        "text-blue-500": index.change < 0,
      })}
    >
      {index.change.toLocaleString(undefined, {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      })}{" "}
      ({index.changeRate.toFixed(2)}%)
    </span>
  </div>
);

export function MarketIndices() {
  const { indices, isLoading, fetchIndices, fetchedAt } = useMarketIndices();

  useEffect(() => {
    fetchIndices();
    const interval = setInterval(fetchIndices, 30000); // 30초마다 새로고침
    return () => clearInterval(interval);
  }, [fetchIndices]);

  if (isLoading && !fetchedAt) {
    return (
      <div className="flex items-center space-x-4">
        <Skeleton className="h-4 w-24" />
        <Skeleton className="h-4 w-24" />
      </div>
    );
  }

  return (
    <div className="hidden items-center space-x-6 md:flex">
      {indices.map((index) => (
        <MarketIndexItem key={index.code} index={index} />
      ))}
    </div>
  );
}
