"use client";

import { Publication } from '@/lib/publications';
import React, { createContext, useContext, useState, ReactNode } from 'react';

interface CitationContextType {
  citedKeys: Set<string>;
  addCitedKey: (key: string) => void;
  getPublicationByKey: (key: string) => Publication | undefined;
}

const CitationContext = createContext<CitationContextType | undefined>(undefined);

export const CitationProvider: React.FC<{ children: ReactNode; publications: Publication[] }> = ({ children, publications }) => {
  const [citedKeys, setCitedKeys] = useState<Set<string>>(new Set());

  const addCitedKey = (key: string) => {
    setCitedKeys(prevKeys => {
      if (prevKeys.has(key)) {
        return prevKeys;
      }
      const newKeys = new Set(prevKeys);
      newKeys.add(key);
      return newKeys;
    });
  };

  const getPublicationByKey = (key: string) => {
    return publications.find(p => p.key === key);
  };

  return (
    <CitationContext.Provider value={{ citedKeys, addCitedKey, getPublicationByKey }}>
      {children}
    </CitationContext.Provider>
  );
};

export const useCitations = (): CitationContextType => {
  const context = useContext(CitationContext);
  if (!context) {
    throw new Error('useCitations must be used within a CitationProvider');
  }
  return context;
};
