/**
 * ConfirmModal — кастомная модалка подтверждения вместо window.confirm.
 *
 * Использование:
 *   const [confirmState, setConfirmState] = useState(null);
 *   ...
 *   setConfirmState({
 *     title: 'Сменить язык?',
 *     message: '...',
 *     confirmLabel: 'Сменить',
 *     cancelLabel: 'Отмена',
 *     onConfirm: () => doSomething(),
 *   });
 *   ...
 *   {confirmState && <ConfirmModal {...confirmState} onClose={() => setConfirmState(null)} />}
 *
 * Стиль — тёмная тема Рублокс-студии, кнопка confirm заметная.
 */
import React, { useEffect, useRef } from 'react';

export default function ConfirmModal({
    title,
    message,
    confirmLabel = 'OK',
    cancelLabel = 'Отмена',
    confirmTone = 'primary', // 'primary' | 'danger'
    onConfirm,
    onCancel,   // если задан — вызывается при клике на «cancel» вместо тихого закрытия
    onClose,
}) {
    const handleCancel = () => {
        try { onCancel?.(); } finally { onClose?.(); }
    };
    const confirmBtnRef = useRef(null);

    useEffect(() => {
        // Автофокус на кнопке подтверждения
        const t = setTimeout(() => confirmBtnRef.current?.focus(), 50);
        const onKey = (e) => {
            if (e.key === 'Escape') { e.preventDefault(); onClose?.(); }
            else if (e.key === 'Enter') {
                // Enter — confirm только если кнопка в фокусе или ничего не в фокусе
                if (document.activeElement === confirmBtnRef.current || document.activeElement?.tagName === 'BODY') {
                    e.preventDefault();
                    handleConfirm();
                }
            }
        };
        window.addEventListener('keydown', onKey);
        return () => { clearTimeout(t); window.removeEventListener('keydown', onKey); };
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const handleConfirm = () => {
        try { onConfirm?.(); } finally { onClose?.(); }
    };

    return (
        <div
            onClick={onClose}
            style={{
                position: 'fixed',
                inset: 0,
                background: 'rgba(0, 0, 0, 0.55)',
                backdropFilter: 'blur(4px)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                zIndex: 9999,
                fontFamily: '"Roboto Condensed", system-ui, sans-serif',
                animation: 'rbxConfirmFadeIn 140ms ease-out',
            }}
        >
            <style>{`
                @keyframes rbxConfirmFadeIn {
                    from { opacity: 0; }
                    to { opacity: 1; }
                }
                @keyframes rbxConfirmPopIn {
                    from { transform: scale(0.95); opacity: 0; }
                    to { transform: scale(1); opacity: 1; }
                }
            `}</style>
            <div
                onClick={(e) => e.stopPropagation()}
                style={{
                    background: 'linear-gradient(180deg, #2a2a2e 0%, #1f1f22 100%)',
                    border: '1px solid #3a3a40',
                    borderRadius: 14,
                    padding: '22px 26px 18px',
                    minWidth: 380,
                    maxWidth: 480,
                    color: '#e8e8ea',
                    boxShadow: '0 20px 60px rgba(0, 0, 0, 0.55), 0 0 0 1px rgba(255, 255, 255, 0.04)',
                    animation: 'rbxConfirmPopIn 160ms cubic-bezier(0.34, 1.56, 0.64, 1)',
                }}
            >
                {title && (
                    <div style={{
                        fontSize: 16,
                        fontWeight: 800,
                        letterSpacing: -0.2,
                        marginBottom: 10,
                        color: '#fff',
                    }}>
                        {title}
                    </div>
                )}
                {message && (
                    <div style={{
                        fontSize: 13.5,
                        lineHeight: 1.55,
                        color: '#c8c8cc',
                        marginBottom: 20,
                        whiteSpace: 'pre-wrap',
                    }}>
                        {message}
                    </div>
                )}
                <div style={{
                    display: 'flex',
                    justifyContent: 'flex-end',
                    gap: 8,
                }}>
                    <button
                        onClick={handleCancel}
                        style={{
                            padding: '8px 16px',
                            borderRadius: 8,
                            border: '1px solid #3a3a40',
                            background: 'transparent',
                            color: '#c8c8cc',
                            fontSize: 13,
                            fontWeight: 700,
                            fontFamily: 'inherit',
                            cursor: 'pointer',
                            transition: 'all 120ms',
                        }}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.background = '#2e2e34';
                            e.currentTarget.style.color = '#fff';
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.background = 'transparent';
                            e.currentTarget.style.color = '#c8c8cc';
                        }}
                    >
                        {cancelLabel}
                    </button>
                    <button
                        ref={confirmBtnRef}
                        onClick={handleConfirm}
                        style={{
                            padding: '8px 18px',
                            borderRadius: 8,
                            border: 'none',
                            background: confirmTone === 'danger'
                                ? 'linear-gradient(135deg, #ff6f7a 0%, #c0303f 100%)'
                                : 'linear-gradient(135deg, #4f74ff 0%, #3a57d8 100%)',
                            color: '#fff',
                            fontSize: 13,
                            fontWeight: 800,
                            fontFamily: 'inherit',
                            cursor: 'pointer',
                            letterSpacing: 0.2,
                            boxShadow: confirmTone === 'danger'
                                ? '0 6px 16px rgba(192, 48, 63, 0.4)'
                                : '0 6px 16px rgba(79, 116, 255, 0.4)',
                            transition: 'all 120ms',
                            outline: 'none',
                        }}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.filter = 'brightness(1.12)';
                            e.currentTarget.style.transform = 'translateY(-1px)';
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.filter = 'brightness(1)';
                            e.currentTarget.style.transform = 'translateY(0)';
                        }}
                        onFocus={(e) => {
                            e.currentTarget.style.boxShadow = confirmTone === 'danger'
                                ? '0 6px 16px rgba(192, 48, 63, 0.5), 0 0 0 3px rgba(192, 48, 63, 0.35)'
                                : '0 6px 16px rgba(79, 116, 255, 0.5), 0 0 0 3px rgba(79, 116, 255, 0.35)';
                        }}
                        onBlur={(e) => {
                            e.currentTarget.style.boxShadow = confirmTone === 'danger'
                                ? '0 6px 16px rgba(192, 48, 63, 0.4)'
                                : '0 6px 16px rgba(79, 116, 255, 0.4)';
                        }}
                    >
                        {confirmLabel}
                    </button>
                </div>
            </div>
        </div>
    );
}
