"use client";

// 테마 상세 페이지: /themes/{slug}.
// 카드 그리드로 해당 테마 종목을 나열. close/pct_change 없으면 자리만 표시.

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

export default function ThemePage({ params }: { params: { slug: string } }) {
  const { slug } = params;
  const [data, setData] = useState<ThemeDetailResponse | null>(null);
  const [err, setErr] = useState<string | null>(null);

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

  return (
    <main className="mx-auto max-w-5xl px-6 py-8">
      <div className="mb-4">
        <Link href="/" className="text-xs text-zinc-500 hover:text-zinc-300">
          ← 홈
        </Link>
      </div>

      {err && <div className="text-sm text-red-400">테마 로딩 실패: {err}</div>}
      {!data && !err && <div className="text-sm text-zinc-500">테마 로딩 중…</div>}

      {data && (
        <>
          <h1 className="text-2xl font-bold text-zinc-50">{data.name}</h1>
          <p className="mt-1 text-sm text-zinc-400">{data.description}</p>
          <div className="mt-1 text-[11px] text-zinc-600">
            {data.items.length} 종목
          </div>

          <div className="mt-6 grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
            {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 (
                <Link
                  key={m.code}
                  href={`/${m.code}`}
                  className="rounded-lg border border-zinc-800 bg-zinc-900/40 px-3 py-2.5 transition hover:border-zinc-700 hover:bg-zinc-800/60"
                >
                  <div className="flex items-baseline justify-between gap-2">
                    <div className="min-w-0 truncate text-sm font-medium text-zinc-100">
                      {m.name}
                    </div>
                    <div className="shrink-0 text-[11px] text-zinc-500">
                      {m.market ?? "—"}
                    </div>
                  </div>
                  <div className="mt-1 flex items-baseline justify-between text-xs tabular-nums">
                    <span className="text-zinc-200">
                      {m.close != null
                        ? m.close.toLocaleString(undefined, {
                            maximumFractionDigits: 0,
                          })
                        : "—"}
                    </span>
                    <span className={tone}>
                      {pct != null
                        ? `${pct >= 0 ? "+" : ""}${pct.toFixed(2)}%`
                        : ""}
                    </span>
                  </div>
                  <div className="mt-0.5 text-[10px] text-zinc-600">{m.code}</div>
                </Link>
              );
            })}
          </div>
        </>
      )}
    </main>
  );
}
