// components/PDFLightbox.jsx
import React, { useEffect, useRef } from 'react';
import { X, FileText } from 'lucide-react';

const PDFLightbox = ({ pdf, onClose }) => {
    const containerRef = useRef(null);
    const viewerInstanceRef = useRef(null);
    const viewerIdRef = useRef(`pdf-rack-lightbox-${pdf.id}-${Date.now()}`);

    useEffect(() => {
        if (!pdf?.url || !containerRef.current) return;

        const viewerId = viewerIdRef.current;
        const assetsUrl = window.pdfRack?.assetsUrl || '';

        const config = {
            containerId: viewerId,
            pdfUrl: pdf.url,
            assetsUrl: assetsUrl,
        };

        // Create the viewer container element
        const viewerEl = document.createElement('div');
        viewerEl.id = viewerId;
        viewerEl.className = 'pdfrack-viewer-container';
        viewerEl.style.cssText = 'width: 100%; height: 100%;';
        viewerEl.dataset.config = JSON.stringify(config);
        containerRef.current.appendChild(viewerEl);

        // Instantiate the viewer
        const timer = setTimeout(() => {
            try {
                if (window.PDFViewer) {
                    viewerInstanceRef.current = new window.PDFViewer({
                        ...config,
                        containerId: viewerId,
                    });
                    viewerEl.dataset.initialized = 'true';
                }
            } catch (e) {
                console.error('PDFLightbox: Viewer init failed', e);
            }
        }, 50);

        // Lock body scroll
        document.body.style.overflow = 'hidden';

        return () => {
            clearTimeout(timer);
            document.body.style.overflow = '';

            // Destroy viewer instance
            if (viewerInstanceRef.current && typeof viewerInstanceRef.current.destroy === 'function') {
                try {
                    viewerInstanceRef.current.destroy();
                } catch (err) { /* ignore */ }
            }
            viewerInstanceRef.current = null;

            // Cleanup global reference
            if (window.PDFViewerInstances?.[viewerId]) {
                delete window.PDFViewerInstances[viewerId];
            }
        };
    }, [pdf]);

    useEffect(() => {
        const handleEscape = (e) => {
            if (e.key === 'Escape') onClose();
        };
        window.addEventListener('keydown', handleEscape);
        return () => window.removeEventListener('keydown', handleEscape);
    }, [onClose]);

    if (!pdf) return null;

    return (
        <div className="fixed inset-0 z-[99999] flex items-center justify-center p-4 sm:p-10">
            {/* Backdrop */}
            <div
                className="absolute inset-0 bg-slate-900/60 backdrop-blur-sm"
                onClick={onClose}
            />

            {/* Modal Container */}
            <div className="relative z-10 w-full h-full max-w-7xl bg-white rounded-2xl shadow-2xl overflow-hidden flex flex-col animate-in fade-in zoom-in-95 duration-200">
                {/* Header */}
                <div className="flex items-center justify-between px-6 py-4 bg-white border-b border-slate-200">
                    <div className="flex items-center gap-3 min-w-0">
                        <div className="bg-indigo-50 p-2 rounded-lg inline-flex items-center">
                            <FileText className="size-4 text-indigo-600" />
                        </div>
                        <h3 className="text-base font-bold text-slate-900 truncate">
                            {pdf.title || pdf.name}
                        </h3>
                    </div>
                    <button
                        onClick={onClose}
                        className="p-2 text-slate-400 hover:text-slate-900 hover:bg-slate-100 rounded-full transition-all"
                    >
                        <X className="size-5" />
                    </button>
                </div>

                {/* Viewer Area */}
                <div
                    ref={containerRef}
                    className="flex-1 min-h-0 bg-slate-100"
                />
            </div>
        </div>
    );
};

export default PDFLightbox;
