import { useEffect, useState } from "react";
import {
  EVIDENCE_STAFF_REVIEW_ACK_EVENT,
  evidenceStaffReviewAckStorageKey,
  hasEvidenceStaffReviewAcknowledged,
} from "@/components/evidence/evidenceStaffReviewAck";

/**
 * Subscription + hydration for {@link markEvidenceStaffReviewAcknowledged} (same tab + storage).
 */
export function useEvidenceStaffReviewAck(caseId: string | undefined): boolean {
  const [ack, setAck] = useState(() => (caseId ? hasEvidenceStaffReviewAcknowledged(caseId) : false));

  useEffect(() => {
    if (!caseId?.trim()) {
      setAck(false);
      return;
    }
    setAck(hasEvidenceStaffReviewAcknowledged(caseId));

    const handler = (e: Event) => {
      const ce = e as CustomEvent<{ caseId?: string }>;
      if (ce.detail?.caseId === caseId) {
        setAck(hasEvidenceStaffReviewAcknowledged(caseId));
      }
    };

    window.addEventListener(EVIDENCE_STAFF_REVIEW_ACK_EVENT, handler);
    return () => window.removeEventListener(EVIDENCE_STAFF_REVIEW_ACK_EVENT, handler);
  }, [caseId]);

  useEffect(() => {
    if (!caseId?.trim()) return;
    const key = evidenceStaffReviewAckStorageKey(caseId);
    const onStorage = (e: StorageEvent) => {
      if (e.storageArea === sessionStorage && e.key === key) {
        setAck(hasEvidenceStaffReviewAcknowledged(caseId));
      }
    };
    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, [caseId]);

  return ack;
}
