/**
 * In-app notifications: toasts and modal confirm/prompt.
 * Replaces browser alert(), confirm(), prompt() so no "localhost says" popups.
 * Usage: window.otoNotify.toast('Message', 'success'|'error'|'info')
 *        window.otoNotify.confirm({ title, message }).then(ok => ...)
 *        window.otoNotify.prompt({ title, message, defaultValue }).then(value => ...)
 */
(function () {
    if (typeof window !== 'undefined') {
        window.otoNotify = window.otoNotify || {
            toast: function () {},
            confirm: () => Promise.resolve(false),
            prompt: () => Promise.resolve(null),
        };
    }
    const { useState, useEffect, useRef } = React;

    const TOAST_TTL_MS = 4500;

    const OTOToast = ({ item, onDismiss }) => {
        const typeStyles = {
            success: 'bg-emerald-600 text-white border-emerald-700',
            error: 'bg-red-600 text-white border-red-700',
            info: 'bg-primary text-white border-primary-dark',
        };
        const style = typeStyles[item.type] || typeStyles.info;
        useEffect(() => {
            const t = setTimeout(() => onDismiss(item.id), TOAST_TTL_MS);
            return () => clearTimeout(t);
        }, [item.id]);
        return (
            <div
                className={`${style} border rounded-lg shadow-lg px-4 py-3 text-sm font-medium max-w-sm oto-toast-enter flex items-center justify-between gap-3`}
                role="alert"
            >
                <span className="flex-1">{item.message}</span>
                <button
                    type="button"
                    onClick={() => onDismiss(item.id)}
                    className="opacity-80 hover:opacity-100 p-0.5 rounded"
                    aria-label="Dismiss"
                >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
                </button>
            </div>
        );
    };

    const ConfirmModal = ({ title, message, confirmLabel = 'Confirm', cancelLabel = 'Cancel', danger, resolve }) => {
        const resolveRef = useRef(resolve);
        resolveRef.current = resolve;
        useEffect(() => {
            return () => { if (resolveRef.current) resolveRef.current(false); };
        }, []);
        const handleConfirm = () => { resolveRef.current?.(true); resolveRef.current = null; };
        const handleCancel = () => { resolveRef.current?.(false); resolveRef.current = null; };
        return (
            <div className="fixed inset-0 z-[9998] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" onClick={handleCancel}>
                <div className="bg-white rounded-xl shadow-2xl max-w-md w-full p-6 border border-gray-200" onClick={e => e.stopPropagation()}>
                    <h3 className="text-lg font-semibold text-gray-900 mb-2">{title}</h3>
                    <p className="text-gray-600 text-sm mb-6">{message}</p>
                    <div className="flex justify-end gap-3">
                        <button type="button" onClick={handleCancel} className="px-4 py-2 rounded-lg font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 transition-colors">
                            {cancelLabel}
                        </button>
                        <button
                            type="button"
                            onClick={handleConfirm}
                            className={`px-4 py-2 rounded-lg font-medium text-white transition-colors ${danger ? 'bg-red-600 hover:bg-red-700' : 'bg-primary hover:bg-primary-hover'}`}
                        >
                            {confirmLabel}
                        </button>
                    </div>
                </div>
            </div>
        );
    };

    const PromptModal = ({ title, message, defaultValue = '', placeholder, submitLabel = 'Submit', cancelLabel = 'Cancel', resolve }) => {
        const [value, setValue] = useState(defaultValue);
        const resolveRef = useRef(resolve);
        resolveRef.current = resolve;
        const inputRef = useRef(null);
        useEffect(() => { inputRef.current?.focus(); }, []);
        useEffect(() => {
            return () => { if (resolveRef.current) resolveRef.current(null); };
        }, []);
        const handleSubmit = () => { resolveRef.current?.(value.trim() || null); resolveRef.current = null; };
        const handleCancel = () => { resolveRef.current?.(null); resolveRef.current = null; };
        return (
            <div className="fixed inset-0 z-[9998] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" onClick={handleCancel}>
                <div className="bg-white rounded-xl shadow-2xl max-w-md w-full p-6 border border-gray-200" onClick={e => e.stopPropagation()}>
                    <h3 className="text-lg font-semibold text-gray-900 mb-2">{title}</h3>
                    {message && <p className="text-gray-600 text-sm mb-4">{message}</p>}
                    <input
                        ref={inputRef}
                        type="text"
                        value={value}
                        onChange={e => setValue(e.target.value)}
                        onKeyDown={e => { if (e.key === 'Enter') handleSubmit(); if (e.key === 'Escape') handleCancel(); }}
                        placeholder={placeholder}
                        className="w-full border border-gray-300 rounded-lg px-3 py-2 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent mb-6"
                    />
                    <div className="flex justify-end gap-3">
                        <button type="button" onClick={handleCancel} className="px-4 py-2 rounded-lg font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 transition-colors">
                            {cancelLabel}
                        </button>
                        <button type="button" onClick={handleSubmit} className="px-4 py-2 rounded-lg font-medium text-white bg-primary hover:bg-primary-hover transition-colors">
                            {submitLabel}
                        </button>
                    </div>
                </div>
            </div>
        );
    };

    const OTONotifyPortal = () => {
        const [toasts, setToasts] = useState([]);
        const [confirmState, setConfirmState] = useState(null);
        const [promptState, setPromptState] = useState(null);
        const setStateRef = useRef(null);

        useEffect(() => {
            setStateRef.current = { setToasts, setConfirmState, setPromptState };
            window.otoNotify = {
                toast: (message, type = 'info') => {
                    const id = Date.now() + Math.random();
                    setStateRef.current?.setToasts(s => [...s, { id, message: String(message), type }]);
                },
                confirm: (opts = {}) => {
                    return new Promise((resolve) => {
                        setStateRef.current?.setConfirmState({
                            title: opts.title || 'Confirm',
                            message: opts.message || '',
                            confirmLabel: opts.confirmLabel || 'Confirm',
                            cancelLabel: opts.cancelLabel || 'Cancel',
                            danger: !!opts.danger,
                            resolve: (ok) => {
                                setStateRef.current?.setConfirmState(null);
                                resolve(!!ok);
                            },
                        });
                    });
                },
                prompt: (opts = {}) => {
                    return new Promise((resolve) => {
                        setStateRef.current?.setPromptState({
                            title: opts.title || 'Input',
                            message: opts.message || '',
                            defaultValue: opts.defaultValue ?? '',
                            placeholder: opts.placeholder || '',
                            submitLabel: opts.submitLabel || 'Submit',
                            cancelLabel: opts.cancelLabel || 'Cancel',
                            resolve: (value) => {
                                setStateRef.current?.setPromptState(null);
                                resolve(value);
                            },
                        });
                    });
                },
            };
            return () => {
                delete window.otoNotify;
            };
        }, []);

        const dismissToast = (id) => setToasts(s => s.filter(t => t.id !== id));

        return (
            <>
                <div className="fixed bottom-4 right-4 z-[9999] flex flex-col gap-2 pointer-events-none">
                    <div className="flex flex-col gap-2 pointer-events-auto">
                        {toasts.map(item => (
                            <OTOToast key={item.id} item={item} onDismiss={dismissToast} />
                        ))}
                    </div>
                </div>
                {confirmState && (
                    <ConfirmModal
                        title={confirmState.title}
                        message={confirmState.message}
                        confirmLabel={confirmState.confirmLabel}
                        cancelLabel={confirmState.cancelLabel}
                        danger={confirmState.danger}
                        resolve={confirmState.resolve}
                    />
                )}
                {promptState && (
                    <PromptModal
                        title={promptState.title}
                        message={promptState.message}
                        defaultValue={promptState.defaultValue}
                        placeholder={promptState.placeholder}
                        submitLabel={promptState.submitLabel}
                        cancelLabel={promptState.cancelLabel}
                        resolve={promptState.resolve}
                    />
                )}
            </>
        );
    };

    if (typeof window !== 'undefined') window.OTONotifyPortal = OTONotifyPortal;
})();
