"use client";

import React, { useState, useEffect } from "react";
import { ApprovalRequestModal, type ApprovalModalEventDetail } from "./ApprovalRequestModal";

/**
 * 전역 결재 요청 모달 리스너
 *
 * CustomEvent('open-approval-modal')를 수신하여 ApprovalRequestModal을 엽니다.
 *
 * 이벤트 발송 예시:
 * window.dispatchEvent(new CustomEvent('open-approval-modal', {
 *   detail: {
 *     targetTable: 'purchase_orders',
 *     targetRecordId: '123',
 *     targetRecordData: { ... },
 *     definitionId: 1,
 *     screenId: 10,
 *     buttonComponentId: 'btn-approval-001',
 *   }
 * }));
 */
export const ApprovalGlobalListener: React.FC = () => {
  const [open, setOpen] = useState(false);
  const [eventDetail, setEventDetail] = useState<ApprovalModalEventDetail | null>(null);

  useEffect(() => {
    const handleOpenModal = (e: Event) => {
      const customEvent = e as CustomEvent<ApprovalModalEventDetail>;
      setEventDetail(customEvent.detail || null);
      setOpen(true);
    };

    window.addEventListener("open-approval-modal", handleOpenModal);
    return () => {
      window.removeEventListener("open-approval-modal", handleOpenModal);
    };
  }, []);

  return (
    <ApprovalRequestModal
      open={open}
      onOpenChange={(v) => {
        setOpen(v);
        if (!v) setEventDetail(null);
      }}
      eventDetail={eventDetail}
    />
  );
};

export default ApprovalGlobalListener;
