"use client";

// 관심종목 토글 버튼. 종목 페이지 PriceHero 옆에 들어감.
// localStorage 만 건드리므로 백엔드 호출 없음.

import { useEffect, useState } from "react";
import { watchlist } from "../lib/watchlist";

export function StarButton({ code, name }: { code: string; name?: string }) {
  const [active, setActive] = useState(false);

  useEffect(() => {
    setActive(watchlist.has(code));
    return watchlist.subscribe(() => setActive(watchlist.has(code)));
  }, [code]);

  const toggle = () => {
    const now = watchlist.toggle(code);
    setActive(now);
  };

  return (
    <button
      type="button"
      onClick={toggle}
      aria-pressed={active}
      title={active ? "관심종목에서 제거" : "관심종목에 추가"}
      className={`flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs transition ${
        active
          ? "border-amber-500/60 bg-amber-500/10 text-amber-300"
          : "border-zinc-700 bg-zinc-900 text-zinc-400 hover:border-zinc-500 hover:text-zinc-200"
      }`}
    >
      <span aria-hidden>{active ? "★" : "☆"}</span>
      <span>{active ? "관심" : "관심"}</span>
      {name && <span className="sr-only">{name}</span>}
    </button>
  );
}
