// Toast Notification Component
function ToastContainer({ toasts, removeToast }) {
    return (
        <div className="fixed top-4 right-4 z-[9999] space-y-2 pointer-events-none">
            {toasts.map(toast => (
                <div 
                    key={toast.id}
                    className={`pointer-events-auto min-w-[300px] max-w-md p-4 rounded-lg shadow-lg border-l-4 flex items-start gap-3 transform transition-all duration-300 animate-slide-in ${
                        toast.type === 'success' ? 'bg-white border-emerald-500 text-gray-800' :
                        toast.type === 'error' ? 'bg-white border-red-500 text-gray-800' :
                        'bg-white border-blue-500 text-gray-800'
                    }`}
                >
                    <div className={`mt-0.5 ${
                        toast.type === 'success' ? 'text-emerald-500' :
                        toast.type === 'error' ? 'text-red-500' :
                        'text-blue-500'
                    }`}>
                        {toast.type === 'success' ? <span className="icon-circle-check"></span> :
                         toast.type === 'error' ? <span className="icon-circle-alert"></span> :
                         <span className="icon-info"></span>}
                    </div>
                    <div className="flex-1">
                        <h4 className="font-bold text-sm">{toast.title}</h4>
                        <p className="text-xs text-gray-500 mt-1">{toast.message}</p>
                    </div>
                    <button onClick={() => removeToast(toast.id)} className="text-gray-400 hover:text-gray-600">
                        <span className="icon-x w-4 h-4"></span>
                    </button>
                </div>
            ))}
        </div>
    );
}

// Reusable Modal Component
function Modal({ title, isOpen, onClose, children, size = 'md' }) {
    if (!isOpen) return null;

    const sizeClasses = {
        sm: 'max-w-sm',
        md: 'max-w-md',
        lg: 'max-w-lg',
        xl: 'max-w-xl',
        '2xl': 'max-w-2xl',
        '4xl': 'max-w-4xl'
    };

    return (
        <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4 backdrop-blur-sm animate-fade-in">
            <div className={`bg-white rounded-xl shadow-xl w-full ${sizeClasses[size]} overflow-hidden flex flex-col max-h-[90vh]`}>
                <div className="p-5 border-b border-gray-100 bg-gray-50 flex justify-between items-center flex-shrink-0">
                    <h3 className="font-bold text-gray-900">{title}</h3>
                    <button onClick={onClose} className="hover:bg-gray-200 p-1 rounded-full transition-colors">
                        <span className="icon-x text-gray-500"></span>
                    </button>
                </div>
                <div className="overflow-y-auto custom-scrollbar">
                    {children}
                </div>
            </div>
        </div>
    );
}

// Confirmation Modal
function ConfirmModal({ isOpen, title, message, onConfirm, onCancel, confirmText = 'Confirm', type = 'danger' }) {
    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-[60] bg-black/50 flex items-center justify-center p-4 backdrop-blur-sm">
            <div className="bg-white rounded-xl shadow-2xl max-w-sm w-full p-6 text-center animate-scale-in">
                <div className={`w-14 h-14 rounded-full flex items-center justify-center mx-auto mb-4 ${
                    type === 'danger' ? 'bg-red-100 text-red-600' : 'bg-blue-100 text-blue-600'
                }`}>
                    <span className={`text-2xl ${type === 'danger' ? 'icon-triangle-alert' : 'icon-info'}`}></span>
                </div>
                <h3 className="text-lg font-bold text-gray-900 mb-2">{title}</h3>
                <p className="text-gray-500 text-sm mb-6">{message}</p>
                <div className="flex gap-3">
                    <button onClick={onCancel} className="flex-1 py-2.5 rounded-lg border border-gray-300 font-medium text-gray-700 hover:bg-gray-50 transition-colors">
                        Cancel
                    </button>
                    <button onClick={onConfirm} className={`flex-1 py-2.5 rounded-lg font-bold text-white shadow-lg transition-transform active:scale-95 ${
                        type === 'danger' ? 'bg-red-600 hover:bg-red-700 shadow-red-500/30' : 'bg-blue-600 hover:bg-blue-700 shadow-blue-500/30'
                    }`}>
                        {confirmText}
                    </button>
                </div>
            </div>
        </div>
    );
}

// ─── Global Dialog Host ───────────────────────────────────────────────────────
// Renders all custom popups as React modals and exposes window.AppDialog API.
// Must be rendered once at the App root.
function DialogHost() {
    const [dialog, setDialog] = React.useState(null);
    const [promptValue, setPromptValue] = React.useState('');
    const inputRef = React.useRef(null);

    React.useEffect(() => {
        // Expose API globally
        window.AppDialog = {
            // alert(title, message, type='info') → Promise<void>
            alert: (title, message, type = 'info') => new Promise(resolve => {
                setDialog({ kind: 'alert', title, message, type, resolve });
            }),
            // confirm(title, message, confirmText, type) → Promise<boolean>
            confirm: (title, message, confirmText = 'Confirm', type = 'danger') => new Promise(resolve => {
                setDialog({ kind: 'confirm', title, message, confirmText, type, resolve });
            }),
            // prompt(title, message, placeholder, defaultValue) → Promise<string|null>
            prompt: (title, message, placeholder = '', defaultValue = '') => new Promise(resolve => {
                setPromptValue(defaultValue);
                setDialog({ kind: 'prompt', title, message, placeholder, resolve });
            }),
        };
    }, []);

    React.useEffect(() => {
        if (dialog && dialog.kind === 'prompt' && inputRef.current) {
            setTimeout(() => inputRef.current && inputRef.current.focus(), 50);
        }
    }, [dialog]);

    const close = (result) => {
        if (dialog) dialog.resolve(result);
        setDialog(null);
        setPromptValue('');
    };

    if (!dialog) return null;

    // Icon and colour based on type
    const typeConfig = {
        info:    { icon: 'icon-info',           ring: 'bg-blue-100 text-blue-600',   btn: 'bg-blue-600 hover:bg-blue-700 shadow-blue-500/30' },
        success: { icon: 'icon-circle-check',   ring: 'bg-emerald-100 text-emerald-600', btn: 'bg-emerald-600 hover:bg-emerald-700 shadow-emerald-500/30' },
        warning: { icon: 'icon-triangle-alert', ring: 'bg-amber-100 text-amber-600', btn: 'bg-amber-500 hover:bg-amber-600 shadow-amber-400/30' },
        danger:  { icon: 'icon-circle-alert',   ring: 'bg-red-100 text-red-600',     btn: 'bg-red-600 hover:bg-red-700 shadow-red-500/30' },
    };
    const cfg = typeConfig[dialog.type || 'info'] || typeConfig.info;

    return (
        <div className="fixed inset-0 z-[9998] bg-black/50 flex items-center justify-center p-4 backdrop-blur-sm animate-fade-in"
             onKeyDown={(e) => {
                 if (e.key === 'Escape') close(dialog.kind === 'confirm' ? false : null);
                 if (e.key === 'Enter' && dialog.kind !== 'prompt') close(dialog.kind === 'confirm' ? true : undefined);
             }}
             tabIndex={-1}
        >
            <div className="bg-white rounded-2xl shadow-2xl max-w-sm w-full overflow-hidden animate-scale-in">

                {/* Header stripe with icon */}
                <div className={`px-6 pt-7 pb-4 flex flex-col items-center text-center`}>
                    <div className={`w-16 h-16 rounded-full flex items-center justify-center mb-4 ${cfg.ring}`}>
                        <span className={`text-3xl ${cfg.icon}`}></span>
                    </div>
                    <h3 className="text-lg font-bold text-gray-900 mb-1">{dialog.title}</h3>
                    <p className="text-sm text-gray-500 leading-relaxed">{dialog.message}</p>
                </div>

                {/* Prompt input */}
                {dialog.kind === 'prompt' && (
                    <div className="px-6 pb-2">
                        <input
                            ref={inputRef}
                            type={dialog.title && dialog.title.toLowerCase().includes('pin') ? 'password' : 'text'}
                            className="w-full px-4 py-3 rounded-xl border-2 border-gray-200 focus:border-[var(--primary)] focus:ring-2 focus:ring-[var(--primary)]/20 outline-none text-center text-lg font-mono tracking-widest transition-all"
                            placeholder={dialog.placeholder}
                            value={promptValue}
                            onChange={e => setPromptValue(e.target.value)}
                            onKeyDown={e => { if (e.key === 'Enter') close(promptValue); }}
                        />
                    </div>
                )}

                {/* Actions */}
                <div className="px-6 pb-6 pt-4 flex gap-3">
                    {/* Cancel / secondary button */}
                    {(dialog.kind === 'confirm' || dialog.kind === 'prompt') && (
                        <button
                            onClick={() => close(dialog.kind === 'confirm' ? false : null)}
                            className="flex-1 py-2.5 rounded-xl border-2 border-gray-200 font-semibold text-gray-600 hover:bg-gray-50 transition-colors"
                        >
                            Cancel
                        </button>
                    )}

                    {/* Primary action */}
                    <button
                        onClick={() => {
                            if (dialog.kind === 'alert') close(undefined);
                            else if (dialog.kind === 'confirm') close(true);
                            else if (dialog.kind === 'prompt') close(promptValue);
                        }}
                        className={`flex-1 py-2.5 rounded-xl font-bold text-white shadow-lg transition-all active:scale-95 ${cfg.btn}`}
                    >
                        {dialog.kind === 'alert' ? 'OK' :
                         dialog.kind === 'confirm' ? (dialog.confirmText || 'Confirm') :
                         'Submit'}
                    </button>
                </div>
            </div>
        </div>
    );
}