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

const STAMP_KEY = 'hr_office_stamp_b64';
const SIGNATURE_KEY = 'hr_officer_signature_b64';

export function getHRStamp(): string | null {
  if (typeof window === 'undefined') return null;
  return localStorage.getItem(STAMP_KEY);
}

export function getHRSignature(): string | null {
  if (typeof window === 'undefined') return null;
  return localStorage.getItem(SIGNATURE_KEY);
}

interface HRStampStore {
  stamp: string | null;
  signature: string | null;
  setStamp: (b64: string | null) => void;
  setSignature: (b64: string | null) => void;
}

const HRStampContext = createContext<HRStampStore | undefined>(undefined);

export function HRStampProvider({ children }: { children: ReactNode }) {
  const [stamp, setStampState] = useState<string | null>(null);
  const [signature, setSignatureState] = useState<string | null>(null);

  useEffect(() => {
    setStampState(localStorage.getItem(STAMP_KEY));
    setSignatureState(localStorage.getItem(SIGNATURE_KEY));
  }, []);

  const setStamp = (b64: string | null) => {
    setStampState(b64);
    if (b64) localStorage.setItem(STAMP_KEY, b64);
    else localStorage.removeItem(STAMP_KEY);
  };

  const setSignature = (b64: string | null) => {
    setSignatureState(b64);
    if (b64) localStorage.setItem(SIGNATURE_KEY, b64);
    else localStorage.removeItem(SIGNATURE_KEY);
  };

  return (
    <HRStampContext.Provider value={{ stamp, signature, setStamp, setSignature }}>
      {children}
    </HRStampContext.Provider>
  );
}

export function useHRStamp() {
  const ctx = useContext(HRStampContext);
  if (!ctx) throw new Error('useHRStamp must be used within HRStampProvider');
  return ctx;
}