import { useEffect } from "react";
import { CODEX_ENTRIES } from "../../data/codex.js";
import { useGame } from "../../context/GameContext.js";

interface CodexToastItemProps {
  entryId: string;
  onDismiss: (id: string) => void;
}

const CodexToastItem = ({ entryId, onDismiss }: CodexToastItemProps): React.JSX.Element | null => {
  const entry = CODEX_ENTRIES.find((e) => e.id === entryId);

  useEffect(() => {
    const timer = setTimeout(() => {
      onDismiss(entryId);
    }, 4000);
    return () => { clearTimeout(timer); };
  }, [entryId, onDismiss]);

  if (!entry) return null;

  return (
    <div className="codex-toast" onClick={() => { onDismiss(entryId); }}>
      <span className="toast-icon">📖</span>
      <div className="toast-content">
        <span className="toast-label">✨ Lore Unlocked!</span>
        <span className="toast-name">{entry.title}</span>
      </div>
    </div>
  );
};

export const CodexToast = (): React.JSX.Element | null => {
  const { newCodexEntryIds, dismissCodexEntry } = useGame();

  if (newCodexEntryIds.length === 0) return null;

  return (
    <div className="achievement-toast-container">
      {newCodexEntryIds.map((id) => (
        <CodexToastItem key={id} entryId={id} onDismiss={dismissCodexEntry} />
      ))}
    </div>
  );
};
