"use client";

// 같은 시장 내 거래량/유동성 기준 관련 종목 8개.
// /api/markets/related/{code} 응답을 좁은 list 카드로 렌더.

import Link from "next/link";
import { useEffect, useState } from "react";
import { api, type RelatedResponse } from "../lib/api";

export function RelatedStocks({ code }: { code: string }) {
  const [data, setData] = useState<RelatedResponse | null>(null);
  const [err, setErr] = useState<string | null>(null);

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

  if (err)
    return (
      <div className="rounded-md border border-zinc-800 bg-zinc-900/40 p-4 text-xs text-zinc-500">
        관련 종목 로딩 실패: {err}
      </div>
    );
  if (!data)
    return (
      <div className="rounded-md border border-zinc-800 bg-zinc-900/40 p-4 text-xs text-zinc-500">
        관련 종목 로딩 중…
      </div>
    );
  if (!data.items.length)
    return (
      <div className="rounded-md border border-zinc-800 bg-zinc-900/40 p-4 text-xs text-zinc-500">
        같은 시장({data.market}) 데이터가 아직 부족합니다.
      </div>
    );

  return (
    <div className="rounded-md border border-zinc-800 bg-zinc-900/40 p-4">
      <div className="mb-2 flex items-baseline justify-between">
        <div className="text-sm font-medium text-zinc-200">관련 종목</div>
        <div className="text-[11px] text-zinc-500">{data.market} · 거래량 기준</div>
      </div>
      <ul className="divide-y divide-zinc-800">
        {data.items.map((m) => {
          const pct = m.pct_change;
          const tone =
            pct == null || pct === 0
              ? "text-zinc-400"
              : pct > 0
              ? "text-rose-400"
              : "text-sky-400";
          return (
            <li key={m.code}>
              <Link
                href={`/${m.code}`}
                className="flex items-center justify-between gap-2 py-1.5 text-xs hover:bg-zinc-800/40"
              >
                <span className="min-w-0 truncate text-zinc-100">{m.name}</span>
                <span className="shrink-0 text-right tabular-nums">
                  <span className="text-zinc-100">
                    {m.close != null
                      ? m.close.toLocaleString(undefined, { maximumFractionDigits: 0 })
                      : "—"}
                  </span>
                  <span className={`ml-2 ${tone}`}>
                    {pct != null
                      ? `${pct >= 0 ? "+" : ""}${pct.toFixed(2)}%`
                      : ""}
                  </span>
                </span>
              </Link>
            </li>
          );
        })}
      </ul>
    </div>
  );
}
