"use client";

// 홈에 들어가는 '테마로 골라보기' 그리드.
// /api/themes 인덱스를 받아 카드로 펼치고, 카드 클릭 시 /themes/{slug} 로 이동.

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

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

  useEffect(() => {
    let alive = true;
    api
      .themesIndex()
      .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>
    );

  return (
    <div>
      <div className="mb-3 flex items-baseline justify-between">
        <h2 className="text-sm font-semibold text-zinc-200">테마로 골라보기</h2>
        <span className="text-[11px] text-zinc-500">{data.total} 카테고리</span>
      </div>
      <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 md:grid-cols-4">
        {data.items.map((t) => (
          <Link
            key={t.slug}
            href={`/themes/${t.slug}`}
            className="group 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="text-sm font-medium text-zinc-100 group-hover:text-rose-300">
              {t.name}
            </div>
            <div className="mt-0.5 truncate text-[11px] text-zinc-500">
              {t.description}
            </div>
            <div className="mt-1 text-[10px] text-zinc-600">
              {t.code_count} 종목
            </div>
          </Link>
        ))}
      </div>
    </div>
  );
}
