"use client";

import { useEffect, useState } from "react";
import { api, type NewsResponse } from "../lib/api";

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

  useEffect(() => {
    let alive = true;
    api
      .news(code, 20)
      .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="text-xs text-red-400">뉴스 로딩 실패: {err}</div>;
  if (!data) return <div className="text-xs text-zinc-500">뉴스 로딩 중…</div>;
  if (!data.items.length)
    return <div className="text-xs text-zinc-500">최근 뉴스 없음</div>;

  return (
    <div className="rounded-md border border-zinc-800 bg-zinc-900/40 p-4">
      <div className="mb-2 text-sm font-medium text-zinc-200">최근 뉴스/공시</div>
      <ul className="divide-y divide-zinc-800">
        {data.items.map((n, i) => (
          <li key={i} className="py-2">
            <a
              href={n.url}
              target="_blank"
              rel="noopener noreferrer"
              className="block hover:bg-zinc-800/40"
            >
              <div className="text-sm text-zinc-100 line-clamp-2">{n.title}</div>
              <div className="mt-0.5 flex items-center gap-2 text-xs text-zinc-500">
                <span>{n.source}</span>
                {n.published_at && <span>· {formatDate(n.published_at)}</span>}
                {n.sentiment_label && (
                  <span className={sentimentColor(n.sentiment_label)}>
                    · {n.sentiment_label} {n.sentiment_score != null ? `(${n.sentiment_score.toFixed(2)})` : ""}
                  </span>
                )}
              </div>
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}

function sentimentColor(l: string): string {
  if (l === "positive") return "text-emerald-400";
  if (l === "negative") return "text-red-400";
  return "text-zinc-400";
}

function formatDate(iso: string): string {
  try {
    const d = new Date(iso);
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
  } catch {
    return iso;
  }
}

function pad(n: number): string {
  return n < 10 ? `0${n}` : `${n}`;
}
