"use client";

// /watchlist — localStorage 의 관심종목 코드들을 카드 그리드로.
// SEED 타일과 같은 톤. 각 카드는 /api/chart 2일치를 받아 현재가/전일대비를 채움.

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

type Tile = {
  code: string;
  name: string;
  market: string;
  current: number | null;
  prev: number | null;
};

export default function WatchlistPage() {
  const [codes, setCodes] = useState<string[]>([]);
  const [tiles, setTiles] = useState<Tile[]>([]);
  const [loading, setLoading] = useState(true);
  const [hydrated, setHydrated] = useState(false);

  // localStorage 구독 — 다른 탭/페이지에서 추가/제거해도 즉시 반영.
  useEffect(() => {
    setHydrated(true);
    const refresh = () => setCodes(watchlist.get());
    refresh();
    return watchlist.subscribe(refresh);
  }, []);

  useEffect(() => {
    if (!hydrated) return;
    if (codes.length === 0) {
      setTiles([]);
      setLoading(false);
      return;
    }
    let alive = true;
    setLoading(true);
    Promise.allSettled(
      codes.map(async (code) => {
        const c = await api.getChart(code, 5, "1d");
        const valid = c.ohlcv.filter((p) => p.close != null);
        const last = valid[valid.length - 1] ?? null;
        const prev = valid.length >= 2 ? valid[valid.length - 2] : null;
        return {
          code,
          name: c.name,
          market: c.market,
          current: last?.close ?? null,
          prev: prev?.close ?? null,
        };
      }),
    ).then((settled) => {
      if (!alive) return;
      const next: Tile[] = settled.map((r, i) => {
        if (r.status === "fulfilled") return r.value;
        return {
          code: codes[i],
          name: codes[i],
          market: "—",
          current: null,
          prev: null,
        };
      });
      setTiles(next);
      setLoading(false);
    });
    return () => {
      alive = false;
    };
  }, [codes, hydrated]);

  return (
    <main className="mx-auto max-w-5xl px-6 py-8">
      <div className="mb-4 flex items-center justify-between gap-3">
        <Link href="/" className="text-xs text-zinc-500 hover:text-zinc-300">
          ← 홈
        </Link>
        <span className="text-[11px] text-zinc-500">{codes.length} 종목</span>
      </div>

      <h1 className="text-2xl font-bold text-zinc-50">관심종목</h1>
      <p className="mt-1 text-sm text-zinc-400">
        브라우저 저장소에 보관됩니다. 로그인 없이 같은 브라우저에서 유지.
      </p>

      <div className="mt-6">
        {!hydrated || loading ? (
          <div className="rounded-md border border-zinc-800 bg-zinc-900/40 p-4 text-xs text-zinc-500">
            관심종목 로딩 중…
          </div>
        ) : codes.length === 0 ? (
          <div className="rounded-md border border-zinc-800 bg-zinc-900/40 p-6 text-center text-sm text-zinc-500">
            아직 관심종목이 없습니다.
            <br />
            종목 페이지에서 <b className="text-amber-300">☆ 관심</b> 버튼을 눌러 추가하세요.
          </div>
        ) : (
          <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 md:grid-cols-4">
            {tiles.map((t) => (
              <TileCard key={t.code} t={t} />
            ))}
          </div>
        )}
      </div>
    </main>
  );
}

function TileCard({ t }: { t: Tile }) {
  const change =
    t.current != null && t.prev != null ? t.current - t.prev : null;
  const pct =
    change != null && t.prev != null && t.prev !== 0
      ? (change / t.prev) * 100
      : null;
  const tone =
    change == null || change === 0
      ? "text-zinc-400"
      : change > 0
      ? "text-rose-400"
      : "text-sky-400";
  return (
    <div className="relative">
      <Link
        href={`/${t.code}`}
        className="block rounded-md border border-zinc-800 bg-zinc-900/40 p-3 transition hover:border-zinc-600"
      >
        <div className="truncate text-sm font-medium text-zinc-100">{t.name}</div>
        <div className="mt-0.5 text-[11px] text-zinc-500">
          {t.code} · {t.market}
        </div>
        <div className="mt-2 text-sm tabular-nums text-zinc-100">
          {t.current != null
            ? t.current.toLocaleString(undefined, { maximumFractionDigits: 0 })
            : "—"}
        </div>
        <div className={`text-[11px] tabular-nums ${tone}`}>
          {change == null
            ? " "
            : `${change > 0 ? "+" : ""}${change.toLocaleString(undefined, {
                maximumFractionDigits: 0,
              })}${pct != null ? ` (${pct > 0 ? "+" : ""}${pct.toFixed(2)}%)` : ""}`}
        </div>
      </Link>
      <button
        type="button"
        onClick={() => watchlist.remove(t.code)}
        title="관심종목에서 제거"
        className="absolute right-1.5 top-1.5 rounded-full bg-zinc-900/80 px-1.5 py-0.5 text-[10px] text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200"
      >
        ✕
      </button>
    </div>
  );
}
