/**
 * Shared Pro upsell modal — portals to document.body for stacking above all Query Forge UI.
 *
 * @package Query_Forge
 */

const { useEffect, useRef } = React;
import { createPortal } from 'react-dom';

/** Above onboarding overlay (100000) and builder shell (99999). */
const MODAL_Z_INDEX = 101000;

function QfProFeatureModal({ title, body, ctaLabel, ctaUrl, onClose }) {
  const dialogRef = useRef(null);
  const titleIdRef = useRef(`qf-pro-feature-modal-title-${Math.random().toString(36).slice(2, 11)}`);
  const titleId = titleIdRef.current;
  const prevActiveRef = useRef(null);
  const onCloseRef = useRef(onClose);

  useEffect(() => {
    onCloseRef.current = onClose;
  }, [onClose]);

  useEffect(() => {
    prevActiveRef.current = document.activeElement;
    const focusDialog = () => {
      const el = dialogRef.current;
      if (el && typeof el.focus === 'function') {
        el.focus();
      }
    };
    const id = window.requestAnimationFrame(() => {
      window.requestAnimationFrame(focusDialog);
    });

    const onKeyDown = (e) => {
      if (e.key === 'Escape') {
        e.preventDefault();
        e.stopPropagation();
        onCloseRef.current();
      }
    };
    document.addEventListener('keydown', onKeyDown, true);

    return () => {
      window.cancelAnimationFrame(id);
      document.removeEventListener('keydown', onKeyDown, true);
      const prev = prevActiveRef.current;
      if (prev && typeof prev.focus === 'function') {
        prev.focus();
      }
    };
  }, []);

  if (typeof document === 'undefined' || !document.body) {
    return null;
  }

  return createPortal(
    <div
      role="presentation"
      style={{
        position: 'fixed',
        inset: 0,
        zIndex: MODAL_Z_INDEX,
        backgroundColor: 'rgba(0, 0, 0, 0.75)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '24px',
      }}
      onMouseDown={(e) => {
        e.stopPropagation();
        if (e.target === e.currentTarget) {
          onCloseRef.current();
        }
      }}
    >
      <div
        ref={dialogRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        tabIndex={-1}
        style={{
          background: '#1e1e1e',
          border: '1px solid #444',
          borderRadius: '8px',
          padding: '28px',
          maxWidth: '480px',
          width: '100%',
          color: '#fff',
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.55)',
          outline: 'none',
        }}
        onMouseDown={(e) => e.stopPropagation()}
      >
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '8px' }}>
          <button
            type="button"
            aria-label="Close"
            onClick={() => onCloseRef.current()}
            style={{
              background: 'transparent',
              border: 'none',
              color: '#a0aec0',
              cursor: 'pointer',
              fontSize: '22px',
              lineHeight: 1,
              padding: '4px 8px',
            }}
          >
            ×
          </button>
        </div>
        <h2 id={titleId} style={{ margin: '0 0 14px 0', fontSize: '20px', fontWeight: 700, color: '#fff' }}>
          {title}
        </h2>
        <p style={{ margin: '0 0 22px 0', fontSize: '14px', color: '#a0aec0', lineHeight: 1.6 }}>{body}</p>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '10px' }}>
          <button
            type="button"
            onClick={() => onCloseRef.current()}
            style={{
              padding: '10px 18px',
              background: 'transparent',
              color: '#fff',
              border: '1px solid #555',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '14px',
            }}
          >
            Close
          </button>
          <a
            href={ctaUrl}
            target="_blank"
            rel="noopener noreferrer"
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              padding: '10px 18px',
              background: '#5c4bde',
              color: '#fff',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '14px',
              fontWeight: 700,
              textDecoration: 'none',
            }}
          >
            {ctaLabel}
          </a>
        </div>
      </div>
    </div>,
    document.body
  );
}

export default QfProFeatureModal;
