function SourceCard({ block, index, onViewInCanvas, bookmarkColor, onSetBookmark, onMoveUp, onMoveDown, isFirst, isLast }) {
    const [copied, setCopied] = useState(false);
    const [showSource, setShowSource] = useState(false);
    const [showBookmarkPicker, setShowBookmarkPicker] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [editedContent, setEditedContent] = useState(block.extracted_text || '');

    const getIconAndLabel = (type) => {
        switch (type) {
            case 'text': return { icon: '📝', label: 'Text Block' };
            case 'image': return { icon: '🖼️', label: 'Image' };
            case 'pdf': return { icon: '📄', label: 'PDF Document' };
            case 'audio': return { icon: '🎤', label: 'Audio Recording' };
            case 'link': return { icon: '🔗', label: 'Link' };
            case 'canvas': return { icon: '✏️', label: 'Canvas Drawing' };
            default: return { icon: '📦', label: 'Content' };
        }
    };

    const { icon, label } = getIconAndLabel(block.content_type);
    const hasExtraction = block.extracted_text && block.extracted_text.trim();

    const copyToClipboard = () => {
        if (hasExtraction) {
            navigator.clipboard.writeText(block.extracted_text);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        }
    };

    const colorMap = { gold: '#FFD700', blue: '#4A90E2', pink: '#FF69B4' };

    return (
        <div
            id={`source-${block.id}`}
            style={{
                position: 'relative',
                background: 'var(--card-bg)',
                border: bookmarkColor ? `2px solid ${colorMap[bookmarkColor]}` : '1px solid var(--border-color)',
                borderRadius: '12px',
                padding: '1.5rem',
                marginBottom: '1rem',
                transition: 'all 0.2s ease',
                boxShadow: bookmarkColor ? `0 0 12px ${colorMap[bookmarkColor]}40` : 'none'
            }}
        >
            {/* Bookmark Ribbon Indicator */}
            {bookmarkColor && (
                <div style={{
                    position: 'absolute',
                    top: 0,
                    right: '1.5rem',
                    width: 0,
                    height: 0,
                    borderLeft: '20px solid transparent',
                    borderRight: '20px solid transparent',
                    borderTop: `35px solid ${colorMap[bookmarkColor]}`,
                    filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.2))'
                }} />
            )}

            {/* Main Layout: Sidebar + Content */}
            <div style={{ display: 'flex', gap: '1rem' }}>
                {/* Left Sidebar - Outside card, absolutely positioned */}
                <div style={{
                    position: 'absolute',
                    left: '-2.5rem',
                    top: '3rem',
                    display: 'flex',
                    flexDirection: 'column',
                    gap: '0.35rem',
                    padding: '0.35rem 0.3rem',
                    background: 'var(--bg-secondary)',
                    border: '1px solid var(--border-color)',
                    borderRadius: '50px',
                    boxShadow: '0 2px 6px rgba(0,0,0,0.1)',
                    zIndex: 10
                }}>
                    {/* Move Up Button */}
                    <button
                        onClick={() => onMoveUp(index)}
                        disabled={isFirst}
                        className="btn"
                        style={{
                            padding: '0.15rem 0.25rem',
                            fontSize: '0.85rem',
                            opacity: isFirst ? 0.3 : 1,
                            cursor: isFirst ? 'not-allowed' : 'pointer',
                            minWidth: '1.5rem',
                            background: 'none',
                            border: 'none',
                            color: 'var(--text-primary)'
                        }}
                        title="Move up"
                    >
                        ↑
                    </button>

                    {/* Move Down Button */}
                    <button
                        onClick={() => onMoveDown(index)}
                        disabled={isLast}
                        className="btn"
                        style={{
                            padding: '0.15rem 0.25rem',
                            fontSize: '0.85rem',
                            opacity: isLast ? 0.3 : 1,
                            cursor: isLast ? 'not-allowed' : 'pointer',
                            minWidth: '1.5rem',
                            background: 'none',
                            border: 'none',
                            color: 'var(--text-primary)'
                        }}
                        title="Move down"
                    >
                        ↓
                    </button>
                    {/* Bookmark Button */}
                    <button
                        onClick={(e) => {
                            e.stopPropagation();
                            setShowBookmarkPicker(!showBookmarkPicker);
                        }}
                        style={{
                            background: 'none',
                            border: 'none',
                            fontSize: '1.15rem',
                            cursor: 'pointer',
                            filter: bookmarkColor ? 'none' : 'grayscale(100%)',
                            opacity: bookmarkColor ? 1 : 0.4,
                            padding: '0.1rem',
                            transition: 'all 0.2s'
                        }}
                        title={bookmarkColor ? `Bookmarked (${bookmarkColor})` : 'Add bookmark'}
                    >
                        🔖
                    </button>

                    {/* Bookmark Color Picker */}
                    {showBookmarkPicker && (
                        <div style={{
                            position: 'absolute',
                            left: '100%',
                            top: '50%',
                            transform: 'translateY(-50%)',
                            marginLeft: '0.5rem',
                            background: 'var(--bg-primary)',
                            border: '1px solid var(--border-color)',
                            borderRadius: '20px',
                            padding: '0.375rem 0.5rem',
                            boxShadow: '0 4px 12px rgba(0,0,0,0.2)',
                            zIndex: 1000,
                            display: 'flex',
                            gap: '0.5rem'
                        }}>
                            {['gold', 'blue', 'pink'].map(color => {
                                const colorFilters = { gold: 'sepia(1) saturate(5) hue-rotate(-10deg)', blue: 'hue-rotate(200deg) saturate(1.5)', pink: 'hue-rotate(300deg) saturate(1.5)' };
                                const isSelected = bookmarkColor === color;

                                return (
                                    <button
                                        key={color}
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            // Toggle: if already selected, remove; otherwise set
                                            onSetBookmark(block.id, isSelected ? null : color);
                                            setShowBookmarkPicker(false);
                                        }}
                                        style={{
                                            background: isSelected ? 'var(--bg-secondary)' : 'none',
                                            border: isSelected ? '2px solid var(--primary)' : '2px solid transparent',
                                            padding: '0.25rem 0.5rem',
                                            cursor: 'pointer',
                                            borderRadius: '12px',
                                            fontSize: '1.25rem',
                                            transition: 'all 0.15s',
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            filter: colorFilters[color]
                                        }}
                                        onMouseEnter={(e) => {
                                            if (!isSelected) e.currentTarget.style.background = 'var(--bg-secondary)';
                                        }}
                                        onMouseLeave={(e) => {
                                            if (!isSelected) e.currentTarget.style.background = 'none';
                                        }}
                                        title={isSelected ? `Remove ${color} bookmark` : `Set ${color} bookmark`}
                                    >
                                        🔖
                                    </button>
                                );
                            })}
                        </div>
                    )}

                    {/* Copy Button */}
                    {hasExtraction && (
                        <button
                            onClick={copyToClipboard}
                            className="btn"
                            style={{ padding: '0.15rem 0.25rem', fontSize: '0.8rem', minWidth: '1.5rem', background: 'none', border: 'none' }}
                            title="Copy extracted content"
                        >
                            {copied ? '✓' : '📋'}
                        </button>
                    )}

                    {/* Edit Button */}
                    {hasExtraction && (
                        <button
                            onClick={() => {
                                setIsEditing(!isEditing);
                                if (isEditing) {
                                    // Save edited content (could add API call here)
                                    block.extracted_text = editedContent;
                                } else {
                                    setEditedContent(block.extracted_text || '');
                                }
                            }}
                            className="btn"
                            style={{
                                padding: '0.15rem 0.25rem',
                                fontSize: '0.8rem',
                                minWidth: '1.5rem',
                                background: isEditing ? 'var(--primary-light)' : 'none',
                                border: 'none',
                                color: isEditing ? 'var(--primary)' : 'inherit'
                            }}
                            title={isEditing ? "Save changes" : "Edit content"}
                        >
                            {isEditing ? '💾' : '✏️'}
                        </button>
                    )}
                </div>

                {/* Right Content Area */}
                <div style={{ flex: 1 }}>

                    {/* Original Preview Toggle */}
                    {((block.content_type === 'image' && block.file_path) || (block.content_type === 'link' && block.content_data?.url)) && (
                        <div style={{ marginBottom: '1rem' }}>
                            <button
                                onClick={() => setShowSource(!showSource)}
                                style={{
                                    background: 'none',
                                    border: 'none',
                                    color: 'var(--primary)',
                                    cursor: 'pointer',
                                    padding: '0',
                                    fontSize: '0.875rem',
                                    fontWeight: '500'
                                }}
                            >
                                {showSource ? 'Hide Source' : 'Source'}
                            </button>

                            {showSource && (
                                <div style={{ marginTop: '0.5rem', animation: 'fadeIn 0.2s' }}>
                                    {block.content_type === 'image' && block.file_path && (
                                        <div style={{ maxWidth: '300px' }}>
                                            <img
                                                src={`/uploads/${block.file_path}`}
                                                alt={block.filename}
                                                style={{ width: '100%', borderRadius: '8px', border: '1px solid var(--border-color)' }}
                                            />
                                        </div>
                                    )}
                                    {block.content_type === 'link' && block.content_data?.url && (
                                        <div>
                                            <a
                                                href={block.content_data.url}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                style={{ color: 'var(--primary)', fontSize: '0.875rem', wordBreak: 'break-all' }}
                                            >
                                                {block.content_data.url}
                                            </a>
                                        </div>
                                    )}

                                    {/* View in RAW button inside Source */}
                                    <div style={{ marginTop: '0.75rem' }}>
                                        <button
                                            onClick={() => onViewInCanvas(block.id)}
                                            style={{
                                                background: 'none',
                                                border: 'none',
                                                color: 'var(--primary)',
                                                cursor: 'pointer',
                                                padding: '0',
                                                fontSize: '0.875rem',
                                                fontWeight: '500'
                                            }}
                                        >
                                            View in RAW →
                                        </button>
                                        <div style={{ marginTop: '0.75rem', borderTop: '1px solid var(--border-color)' }}></div>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}

                    {/* Extracted Content */}
                    <div style={{ marginBottom: '1rem' }}>
                        <div style={{ fontSize: '0.75rem', fontWeight: '600', color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '0.5rem' }}>
                            Extracted Content:
                        </div>
                        {hasExtraction ? (
                            isEditing ? (
                                <div style={{
                                    background: 'var(--bg-secondary)',
                                    padding: '1rem',
                                    borderRadius: '8px',
                                    fontSize: '0.95rem',
                                    lineHeight: '1.6',
                                    border: '2px solid var(--primary)'
                                }}>
                                    <textarea
                                        value={editedContent}
                                        onChange={(e) => setEditedContent(e.target.value)}
                                        style={{
                                            width: '100%',
                                            minHeight: '200px',
                                            border: 'none',
                                            background: 'transparent',
                                            color: 'var(--text-primary)',
                                            fontSize: '0.95rem',
                                            lineHeight: '1.6',
                                            resize: 'vertical',
                                            outline: 'none',
                                            fontFamily: 'inherit'
                                        }}
                                    />
                                    <div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.75rem' }}>
                                        <button
                                            onClick={() => {
                                                block.extracted_text = editedContent;
                                                setIsEditing(false);
                                            }}
                                            className="btn btn-primary"
                                            style={{ padding: '0.375rem 0.75rem', fontSize: '0.875rem' }}
                                        >
                                            Save
                                        </button>
                                        <button
                                            onClick={() => {
                                                setEditedContent(block.extracted_text || '');
                                                setIsEditing(false);
                                            }}
                                            className="btn btn-secondary"
                                            style={{ padding: '0.375rem 0.75rem', fontSize: '0.875rem' }}
                                        >
                                            Cancel
                                        </button>
                                    </div>
                                </div>
                            ) : (
                                <div style={{
                                    background: 'var(--bg-secondary)',
                                    padding: '1rem',
                                    borderRadius: '8px',
                                    fontSize: '0.95rem',
                                    lineHeight: '1.6',
                                    whiteSpace: 'pre-wrap',
                                    color: 'var(--text-primary)'
                                }}>
                                    {block.extracted_text}
                                </div>
                            )
                        ) : (
                            <div style={{
                                padding: '1rem',
                                textAlign: 'center',
                                color: 'var(--text-secondary)',
                                fontStyle: 'italic',
                                fontSize: '0.875rem'
                            }}>
                                No extracted content available
                            </div>
                        )}
                    </div>

                </div> {/* Close content area (flex: 1) */}
            </div> {/* Close flex container (sidebar + content) */}

        </div>
    );
}

// Export to global scope
window.SourceCard = SourceCard;
