"use client";

// 홈 상단에 KOSPI / KOSDAQ 인덱스 두 칸. 우측엔 mini sparkline.
// macro_daily 가 아직 비어 있으면 안내 카드 한 줄.

import { useEffect, useState } from "react";
import { api, type IndicesResponse, type IndexSeries } from "../lib/api";
import { Sparkline } from "./Sparkline";

export function IndicesPanel() {
  const [data, setData] = useState<IndicesResponse | null>(null);
  const [err, setErr] = useState<string | null>(null);

  useEffect(() => {
    let alive = true;
    api
      .indices(60)
      .then((r) => {
        if (alive) setData(r);
      })
      .catch((e) => {
        if (alive) setErr(e instanceof Error ? e.message : String(e));
      });
    return () => {
      alive = false;
    };
  }, []);

  if (err)
    return (
      <div className="rounded-lg border border-zinc-800 bg-zinc-900/30 p-4 text-xs text-zinc-500">
        지수 로딩 실패: {err}
      </div>
    );
  if (!data)
    return (
      <div className="rounded-lg border border-zinc-800 bg-zinc-900/30 p-4 text-xs text-zinc-500">
        지수 로딩 중…
      </div>
    );

  const allEmpty = data.indices.every((s) => s.points.length === 0);
  if (allEmpty)
    return (
      <div className="rounded-lg border border-zinc-800 bg-zinc-900/30 p-4 text-xs text-zinc-500">
        지수 데이터 준비 중. macro_daily 가 채워지면 자동으로 표시됩니다.
      </div>
    );

  return (
    <div className="grid gap-3 md:grid-cols-2">
      {data.indices.map((s) => (
        <IndexCard key={s.key} s={s} />
      ))}
    </div>
  );
}

function IndexCard({ s }: { s: IndexSeries }) {
  const pct = s.pct_change;
  const tone =
    pct == null || pct === 0
      ? "text-zinc-400"
      : pct > 0
      ? "text-rose-400"
      : "text-sky-400";
  const stroke = pct != null && pct < 0 ? "#3b82f6" : "#ef4444";
  const values = s.points.map((p) => p.value);

  return (
    <div className="flex items-center justify-between gap-3 rounded-lg border border-zinc-800 bg-zinc-900/40 p-3">
      <div className="min-w-0">
        <div className="text-xs text-zinc-500">{s.name}</div>
        <div className="mt-0.5 text-xl font-semibold tabular-nums text-zinc-50">
          {s.latest != null
            ? s.latest.toLocaleString(undefined, { maximumFractionDigits: 2 })
            : "—"}
        </div>
        <div className={`mt-0.5 text-xs tabular-nums ${tone}`}>
          {pct != null
            ? `${pct >= 0 ? "+" : ""}${pct.toFixed(2)}%`
            : "—"}
        </div>
      </div>
      {values.length >= 2 && (
        <Sparkline values={values} stroke={stroke} width={120} height={40} />
      )}
    </div>
  );
}
