// components/CopyMenu.jsx
import React, { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { Copy, ChevronDown, ScrollText, GalleryHorizontal, BookOpen, MousePointerClick, SlidersHorizontal } from 'lucide-react';
import { buildShortcode } from '../utils/shortcode';
import { useToast } from './Toast';

const QUICK = [
    { label: 'Reader', icon: ScrollText, options: { mode: 'reader' } },
    { label: 'Slider', icon: GalleryHorizontal, options: { mode: 'slider' } },
    { label: '3D Flipbook', icon: BookOpen, options: { mode: 'flipbook' } },
    { label: 'Popup button', icon: MousePointerClick, options: { mode: 'reader', display: 'lightbox' } },
];

/**
 * Split button: main part copies the default shortcode, the caret opens a
 * menu to copy a specific mode or open the full builder.
 */
const CopyMenu = ({ pdf, onCustomize, size = 'md', label = 'Copy shortcode', className = '' }) => {
    const { copy } = useToast();
    const [open, setOpen] = useState(false);
    const [position, setPosition] = useState(null);
    const ref = useRef(null);
    const menuRef = useRef(null);

    // The menu is position:fixed so table/card overflow can't clip it.
    const toggle = () => {
        if (open) {
            setOpen(false);
            return;
        }
        const rect = ref.current.getBoundingClientRect();
        const menuHeight = 260;
        const openUp = window.innerHeight - rect.bottom < menuHeight && rect.top > menuHeight;
        const menuWidth = 224;
        setPosition({
            left: Math.max(8, Math.min(rect.left, window.innerWidth - menuWidth - 8)),
            ...(openUp ? { bottom: window.innerHeight - rect.top + 6 } : { top: rect.bottom + 6 }),
        });
        setOpen(true);
    };

    useEffect(() => {
        if (!open) return undefined;
        const close = (e) => {
            if (ref.current?.contains(e.target) || menuRef.current?.contains(e.target)) return;
            setOpen(false);
        };
        const esc = (e) => e.key === 'Escape' && setOpen(false);
        const dismiss = () => setOpen(false);
        document.addEventListener('mousedown', close);
        document.addEventListener('keydown', esc);
        window.addEventListener('scroll', dismiss, true);
        window.addEventListener('resize', dismiss);
        return () => {
            document.removeEventListener('mousedown', close);
            document.removeEventListener('keydown', esc);
            window.removeEventListener('scroll', dismiss, true);
            window.removeEventListener('resize', dismiss);
        };
    }, [open]);

    const stop = (fn) => (e) => {
        e.stopPropagation();
        fn();
    };

    const pad = size === 'sm' ? 'py-1.5 text-xs' : 'py-2 text-sm';

    return (
        <div ref={ref} className={`relative flex ${className}`} onClick={(e) => e.stopPropagation()}>
            <button
                type="button"
                onClick={stop(() => copy(buildShortcode(pdf.id)))}
                className={`flex-1 flex items-center justify-center gap-1.5 px-3 whitespace-nowrap ${pad} rounded-l-lg border border-slate-200 bg-white font-medium text-slate-700 hover:bg-indigo-50 hover:text-indigo-700 hover:border-indigo-200 transition-colors`}
                title={buildShortcode(pdf.id)}
            >
                <Copy className="size-3.5" />
                {label}
            </button>
            <button
                type="button"
                onClick={stop(toggle)}
                aria-haspopup="menu"
                aria-expanded={open}
                className={`px-2 ${pad} -ml-px rounded-r-lg border border-slate-200 bg-white text-slate-500 hover:bg-indigo-50 hover:text-indigo-700 hover:border-indigo-200 transition-colors ${open ? 'bg-indigo-50 text-indigo-700 border-indigo-200' : ''}`}
                title="More embed options"
            >
                <ChevronDown className={`size-3.5 transition-transform ${open ? 'rotate-180' : ''}`} />
            </button>

            {open && position && createPortal(
                <div
                    ref={menuRef}
                    onClick={(e) => e.stopPropagation()}
                    role="menu"
                    style={position}
                    className="fixed z-[99995] w-56 rounded-xl bg-white p-1.5 shadow-xl ring-1 ring-slate-900/10 animate-scale-in"
                >
                    <p className="px-2.5 pt-1 pb-1.5 text-[10px] font-semibold uppercase tracking-wider text-slate-400">Copy as</p>
                    {QUICK.map(({ label, icon: Icon, options }) => (
                        <button
                            key={label}
                            role="menuitem"
                            type="button"
                            onClick={stop(() => {
                                copy(buildShortcode(pdf.id, options));
                                setOpen(false);
                            })}
                            className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-sm text-slate-700 hover:bg-slate-100"
                        >
                            <Icon className="size-4 text-slate-400" />
                            {label}
                        </button>
                    ))}
                    {onCustomize && (
                        <>
                            <div className="my-1 h-px bg-slate-100" />
                            <button
                                role="menuitem"
                                type="button"
                                onClick={stop(() => {
                                    setOpen(false);
                                    onCustomize(pdf);
                                })}
                                className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-sm font-medium text-indigo-700 hover:bg-indigo-50"
                            >
                                <SlidersHorizontal className="size-4" />
                                Customize embed…
                            </button>
                        </>
                    )}
                </div>,
                // Portal to the app root: card hover transforms would otherwise
                // become the containing block for position:fixed and clip the menu.
                document.getElementById('pdfrack-admin-app') || document.body,
            )}
        </div>
    );
};

export default CopyMenu;
