import { useContext, createContext, useState, useEffect, type ReactNode } from 'react';

interface TrkContextValue {
  copyMode: boolean;
  setCopyMode: (v: boolean) => void;
  activeId: string | null;
  setActiveId: (id: string | null) => void;
}

// eslint-disable-next-line react-refresh/only-export-components
export const TrkContext = createContext<TrkContextValue | null>(null);

export function TrkProvider({ children }: { children: ReactNode }) {
  const [copyMode, setCopyMode] = useState(false);
  const [activeId, setActiveId] = useState<string | null>(null);

  // 딥링크 처리: #trk=TRK-BADGE-critical-sm
  useEffect(() => {
    const applyHash = () => {
      const hash = window.location.hash;
      const match = hash.match(/#trk=([\w-]+)/);
      if (match) {
        const id = match[1];
        setActiveId(id);
        setTimeout(() => {
          const el = document.querySelector(`[data-trk="${id}"]`);
          if (el) {
            el.scrollIntoView({ behavior: 'smooth', block: 'center' });
          }
        }, 50);
      }
    };
    applyHash();
    window.addEventListener('hashchange', applyHash);
    return () => window.removeEventListener('hashchange', applyHash);
  }, []);

  return (
    <TrkContext.Provider value={{ copyMode, setCopyMode, activeId, setActiveId }}>
      {children}
    </TrkContext.Provider>
  );
}

// eslint-disable-next-line react-refresh/only-export-components
export function useTrk() {
  const ctx = useContext(TrkContext);
  if (!ctx) throw new Error('useTrk must be used within TrkProvider');
  return ctx;
}
