"use client";

import { useState, useCallback, type ReactNode } from "react";
import ConfirmDialog from "@/components/shared/confirm-dialog";

interface ConfirmOptions {
  title: string;
  message: string;
  confirmLabel?: string;
  cancelLabel?: string;
  destructive?: boolean;
}

interface PendingConfirm extends ConfirmOptions {
  resolve: (ok: boolean) => void;
}

// Drop-in replacement for window.confirm() that renders the project's
// <ConfirmDialog>. window.confirm is suppressed in iOS PWA standalone mode,
// so destructive flows that relied on it silently no-op'd. Usage:
//
//   const { confirm, dialog } = useConfirm();
//   const ok = await confirm({ title: "Delete?", message: "..." });
//   if (!ok) return;
//   ...
//   return <>{dialog}{...rest}</>;
//
export function useConfirm() {
  const [pending, setPending] = useState<PendingConfirm | null>(null);

  const confirm = useCallback((opts: ConfirmOptions) => {
    return new Promise<boolean>((resolve) => {
      setPending({ ...opts, resolve });
    });
  }, []);

  const close = useCallback((ok: boolean) => {
    setPending((cur) => {
      if (cur) cur.resolve(ok);
      return null;
    });
  }, []);

  const dialog: ReactNode = pending ? (
    <ConfirmDialog
      open
      title={pending.title}
      message={pending.message}
      confirmLabel={pending.confirmLabel}
      cancelLabel={pending.cancelLabel}
      destructive={pending.destructive ?? true}
      onConfirm={() => close(true)}
      onCancel={() => close(false)}
    />
  ) : null;

  return { confirm, dialog };
}
