// ShareView Component - Complete sharing & collaboration interface
// Tabs: My Shares | Shared with Me | Groups

function ShareView({ token, t, setActiveTab, setActionParams }) {
    const [activeShareTab, setActiveShareTab] = useState('shared-with-me');
    const [myShares, setMyShares] = useState([]);
    const [sharedWithMe, setSharedWithMe] = useState([]);
    const [groups, setGroups] = useState([]);
    const [invitations, setInvitations] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showShareModal, setShowShareModal] = useState(false);
    const [showGroupModal, setShowGroupModal] = useState(false);
    const [showInviteModal, setShowInviteModal] = useState(false);
    const [showViewNoteModal, setShowViewNoteModal] = useState(false);
    const [viewingNote, setViewingNote] = useState(null);
    const [viewingNoteDetails, setViewingNoteDetails] = useState(null);
    const [loadingNoteDetails, setLoadingNoteDetails] = useState(false);
    const [selectedNote, setSelectedNote] = useState(null);
    const [selectedGroup, setSelectedGroup] = useState(null);
    const [friends, setFriends] = useState([]);
    const [selectedFriends, setSelectedFriends] = useState([]);
    const [sharePermission, setSharePermission] = useState('view');

    // Multi-step share modal states
    const [shareModalStep, setShareModalStep] = useState(1); // 1: select notes, 2: select friends
    const [allNotes, setAllNotes] = useState([]);
    const [selectedNotes, setSelectedNotes] = useState([]);
    const [noteSearchQuery, setNoteSearchQuery] = useState('');
    const [loadingNotes, setLoadingNotes] = useState(false);
    const [sharingInProgress, setSharingInProgress] = useState(false);

    useEffect(() => {
        fetchData();
        loadFriends();
    }, [activeShareTab]);

    const fetchData = async () => {
        setLoading(true);
        try {
            if (activeShareTab === 'my-shares') {
                // Fetch only notes that user has shared with others
                const response = await fetch(API_URL + '/notes/my-shared-notes', {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                const data = await response.json();
                setMyShares(data.notes || []);
            } else if (activeShareTab === 'shared-with-me') {
                const response = await fetch(API_URL + '/notes/shared-with-me', {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                const data = await response.json();
                setSharedWithMe(data.notes || []);  // Backend returns "notes", not "shared_notes"
            } else if (activeShareTab === 'groups') {
                // Fetch groups
                const [groupsRes, invitesRes] = await Promise.all([
                    fetch(API_URL + '/groups', {
                        headers: { 'Authorization': `Bearer ${token}` }
                    }),
                    fetch(API_URL + '/invitations', {
                        headers: { 'Authorization': `Bearer ${token}` }
                    })
                ]);
                const groupsData = await groupsRes.json();
                const invitesData = await invitesRes.json();
                setGroups(groupsData.groups || []);
                setInvitations(invitesData.invitations || []);
            }
        } catch (error) {
            console.error('Error fetching share data:', error);
        } finally {
            setLoading(false);
        }
    };

    const loadFriends = async () => {
        try {
            const response = await fetch(API_URL + '/connections/my-friends', {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            setFriends(data.friends || []);
        } catch (err) {
            console.error('Failed to load friends:', err);
        }
    };

    // Share modal functions
    const openShareModal = async () => {
        setShowShareModal(true);
        setShareModalStep(1);
        setSelectedNotes([]);
        setSelectedFriends([]);
        setNoteSearchQuery('');
        setSharePermission('view');

        // Load all notes and friends
        setLoadingNotes(true);
        try {
            const response = await fetch(API_URL + '/notes', {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            setAllNotes(data.notes || []);
        } catch (err) {
            console.error('Failed to load notes:', err);
            alert('Failed to load notes');
        } finally {
            setLoadingNotes(false);
        }

        // Also load friends for step 2
        await loadFriends();
    };

    const toggleNoteSelection = (noteId) => {
        setSelectedNotes(prev =>
            prev.includes(noteId)
                ? prev.filter(id => id !== noteId)
                : [...prev, noteId]
        );
    };

    const toggleFriendSelection = (friendId) => {
        setSelectedFriends(prev =>
            prev.includes(friendId)
                ? prev.filter(id => id !== friendId)
                : [...prev, friendId]
        );
    };

    const submitShare = async () => {
        if (selectedNotes.length === 0 || selectedFriends.length === 0) {
            alert('Please select at least one note and one friend');
            return;
        }

        setSharingInProgress(true);
        try {
            // Share each selected note with all selected friends
            let successCount = 0;
            for (const noteId of selectedNotes) {
                const response = await fetch(API_URL + `/notes/${noteId}/share-with-users`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({
                        user_ids: selectedFriends,
                        permission_level: sharePermission
                    })
                });
                if (response.ok) successCount++;
            }

            alert(`Successfully shared ${successCount} note(s) with ${selectedFriends.length} friend(s)!`);
            setShowShareModal(false);
            fetchData(); // Refresh the shared notes list
        } catch (err) {
            console.error('Share error:', err);
            alert('Failed to share notes. Please try again.');
        } finally {
            setSharingInProgress(false);
        }
    };

    // Filter notes based on search query
    const filteredNotes = allNotes.filter(note =>
        note.title?.toLowerCase().includes(noteSearchQuery.toLowerCase()) ||
        note.subject?.toLowerCase().includes(noteSearchQuery.toLowerCase()) ||
        note.tags?.some(tag => tag.toLowerCase().includes(noteSearchQuery.toLowerCase()))
    );

    const shareNote = async (noteId, permissionLevel) => {
        try {
            const response = await fetch(API_URL + `/notes/${noteId}/share`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    permission_level: permissionLevel,
                    is_public: true,
                    expires_in_days: null
                })
            });
            const data = await response.json();

            // Copy link to clipboard
            const shareUrl = `${window.location.origin}${data.share_url}`;
            navigator.clipboard.writeText(shareUrl);
            alert('Share link copied to clipboard!');

            setShowShareModal(false);
        } catch (error) {
            console.error('Error creating share link:', error);
            alert('Failed to create share link');
        }
    };

    const fetchNoteDetails = async (noteId) => {
        try {
            setLoadingNoteDetails(true);
            const response = await fetch(API_URL + `/notes/${noteId}/shared-view`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });

            if (!response.ok) {
                throw new Error('Failed to fetch note details');
            }

            const data = await response.json();
            console.log('Fetched note details:', data);
            setViewingNoteDetails(data);
            setViewingNote(data.note);  // Keep for compatibility with existing modal
            setShowViewNoteModal(true);
        } catch (error) {
            console.error('Error fetching note details:', error);
            alert('❌ Failed to open note. Please try again.');
        } finally {
            setLoadingNoteDetails(false);
        }
    };

    const copyNote = async (noteId) => {
        try {
            setLoading(true);
            const response = await fetch(API_URL + `/notes/${noteId}/copy-to-my-notes`, {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${token}` }
            });

            if (!response.ok) {
                throw new Error('Failed to copy note');
            }

            const data = await response.json();

            // Close modal if open
            setShowViewNoteModal(false);
            setViewingNote(null);
            setViewingNoteDetails(null);

            alert(`✅ Note copied successfully! ${data.blocks_copied} content blocks copied.`);

            // Navigate to notes tab to see the copied note
            setActiveTab('notes');
        } catch (error) {
            console.error('Error copying note:', error);
            alert('❌ Failed to copy note. Please try again.');
        } finally {
            setLoading(false);
        }
    };

    const shareWithFriends = async () => {
        if (selectedFriends.length === 0) {
            alert('Please select at least one friend to share with');
            return;
        }

        try {
            const response = await fetch(API_URL + `/notes/${selectedNote.id}/share-with-users`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    user_ids: selectedFriends,
                    permission_level: sharePermission
                })
            });

            if (response.ok) {
                alert(`Note shared with ${selectedFriends.length} friend(s)!`);
                setShowShareModal(false);
                setSelectedFriends([]);
                setSharePermission('view');
            } else {
                alert('Failed to share note');
            }
        } catch (error) {
            console.error('Error sharing with friends:', error);
            alert('Failed to share note');
        }
    };

    const acceptInvitation = async (invitationId) => {
        try {
            const response = await fetch(API_URL + `/invitations/${invitationId}/accept`, {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${token}` }
            });
            alert('Invitation accepted!');
            fetchData();
        } catch (error) {
            console.error('Error accepting invitation:', error);
            alert('Failed to accept invitation');
        }
    };

    const declineInvitation = async (invitationId) => {
        try {
            await fetch(API_URL + `/invitations/${invitationId}/decline`, {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${token}` }
            });
            fetchData();
        } catch (error) {
            console.error('Error declining invitation:', error);
        }
    };

    const createGroup = async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const groupData = {
            name: formData.get('groupName'),
            description: formData.get('groupDescription'),
            is_private: formData.get('isPrivate') === 'on'
        };

        try {
            const response = await fetch(API_URL + '/groups/create', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(groupData)
            });
            const data = await response.json();
            alert(`Group created! Join code: ${data.join_code}`);
            setShowGroupModal(false);
            fetchData();
        } catch (error) {
            console.error('Error creating group:', error);
            alert('Failed to create group');
        }
    };

    const inviteMembers = async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const emailsText = formData.get('emails');
        const emails = emailsText.split(',').map(e => e.trim()).filter(e => e);

        if (emails.length === 0) {
            alert('Please enter at least one email address');
            return;
        }

        try {
            const response = await fetch(API_URL + `/groups/${selectedGroup.id}/invite`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ emails })
            });
            const data = await response.json();
            alert(data.message);
            setShowInviteModal(false);
            setSelectedGroup(null);
        } catch (error) {
            console.error('Error inviting members:', error);
            alert('Failed to send invitations');
        }
    };


    if (loading) {
        return <div className="loading" style={{ padding: '2rem', textAlign: 'center' }}>Loading...</div>;
    }

    return (
        <div className="fade-in" style={{ padding: '2rem', maxWidth: '1200px', margin: '0 auto' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2rem' }}>
                <h2 className="page-title" style={{ margin: 0 }}>Share Notes</h2>
                {activeShareTab === 'groups' && (
                    <button onClick={() => setShowGroupModal(true)} className="btn btn-primary">
                        + Create Group
                    </button>
                )}
            </div>

            {/* Tab Navigation */}
            <div style={{ display: 'flex', gap: '1rem', marginBottom: '2rem', borderBottom: '2px solid var(--border-color)' }}>
                {['shared-with-me', 'my-shares', 'groups', 'find-people'].map(tab => (
                    <button
                        key={tab}
                        onClick={() => setActiveShareTab(tab)}
                        style={{
                            padding: '0.75rem 1.5rem',
                            border: 'none',
                            background: 'none',
                            color: activeShareTab === tab ? 'var(--primary)' : 'var(--text-secondary)',
                            borderBottom: activeShareTab === tab ? '3px solid var(--primary)' : '3px solid transparent',
                            cursor: 'pointer',
                            fontWeight: activeShareTab === tab ? '600' : '400',
                            fontSize: '15px',
                            transition: 'all 0.2s ease'
                        }}
                    >
                        {tab === 'shared-with-me' ? 'Shared with Me' : tab === 'my-shares' ? 'Share' : tab === 'groups' ? 'Groups' : '🔍 Find People'}
                    </button>
                ))}
            </div>

            {/* Share Tab - Sharing Activity */}
            {activeShareTab === 'my-shares' && (
                <div>
                    {/* Share New Notes Button */}
                    <div style={{ marginBottom: '2rem', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <h3 style={{ fontSize: '18px', fontWeight: '600', margin: 0 }}>My Sharing Activity</h3>
                        <button
                            onClick={openShareModal}
                            className="btn btn-primary"
                            style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}
                        >
                            <span style={{ fontSize: '18px' }}>+</span>
                            Share Notes
                        </button>
                    </div>

                    {myShares.length === 0 ? (
                        <div className="card" style={{ textAlign: 'center', padding: '3rem' }}>
                            <div style={{ fontSize: '64px', marginBottom: '1rem' }}>📤</div>
                            <h3 style={{ marginBottom: '0.5rem', fontSize: '20px' }}>Start Sharing Your Knowledge</h3>
                            <p style={{ color: 'var(--text-secondary)', marginBottom: '2rem', maxWidth: '400px', margin: '0 auto' }}>
                                Share your notes with friends to collaborate and exchange ideas. Click the button above to get started!
                            </p>
                        </div>
                    ) : (
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                            {myShares.map(note => (
                                <div key={note.id} className="card" style={{ padding: '1.5rem', border: '2px solid var(--border-color)' }}>
                                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: '1rem' }}>
                                        <div style={{ flex: 1 }}>
                                            <h3 style={{ fontSize: '18px', fontWeight: '600', marginBottom: '0.5rem', color: 'var(--text-primary)' }}>
                                                📝 {note.title}
                                            </h3>
                                            {note.subject && (
                                                <span style={{
                                                    display: 'inline-block',
                                                    padding: '0.25rem 0.75rem',
                                                    background: 'var(--primary-light)',
                                                    color: 'var(--primary)',
                                                    borderRadius: '12px',
                                                    fontSize: '12px',
                                                    fontWeight: '500'
                                                }}>
                                                    {note.subject}
                                                </span>
                                            )}
                                        </div>
                                        <button
                                            onClick={openShareModal}
                                            className="btn btn-secondary"
                                            style={{ fontSize: '14px', padding: '0.5rem 1rem' }}
                                        >
                                            + Share More
                                        </button>
                                    </div>

                                    {/* Sharing stats */}
                                    <div style={{
                                        display: 'flex',
                                        gap: '2rem',
                                        padding: '1rem',
                                        background: 'var(--bg-secondary)',
                                        borderRadius: '8px',
                                        fontSize: '14px'
                                    }}>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                                            <span style={{ fontSize: '20px' }}>👥</span>
                                            <span style={{ color: 'var(--text-secondary)' }}>
                                                Shared with <strong style={{ color: 'var(--text-primary)' }}>{note.share_count || 0}</strong> {(note.share_count || 0) === 1 ? 'person' : 'people'}
                                            </span>
                                        </div>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                                            <span style={{ fontSize: '20px' }}>📦</span>
                                            <span style={{ color: 'var(--text-secondary)' }}>
                                                <strong style={{ color: 'var(--text-primary)' }}>{note.block_count || 0}</strong> content blocks
                                            </span>
                                        </div>
                                        {note.created_at && (
                                            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                                                <span style={{ fontSize: '20px' }}>📅</span>
                                                <span style={{ color: 'var(--text-secondary)' }}>
                                                    Created {new Date(note.created_at).toLocaleDateString()}
                                                </span>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            )}

            {/* Shared with Me Tab */}
            {activeShareTab === 'shared-with-me' && (
                <div>
                    {sharedWithMe.length === 0 ? (
                        <div className="card" style={{ textAlign: 'center', padding: '3rem' }}>
                            <div style={{ fontSize: '48px', marginBottom: '1rem' }}>📥</div>
                            <h3 style={{ marginBottom: '0.5rem' }}>No shared notes</h3>
                            <p style={{ color: 'var(--text-secondary)' }}>
                                Notes shared with you by others will appear here
                            </p>
                        </div>
                    ) : (
                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '1rem' }}>
                            {sharedWithMe.map(note => (
                                <div key={note.id} className="card" style={{ padding: '1.5rem' }}>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '0.75rem' }}>
                                        <span style={{ fontSize: '20px' }}>👤</span>
                                        <span style={{ fontSize: '13px', color: 'var(--text-secondary)' }}>
                                            {note.owner_name || note.owner_username || 'Someone'}
                                        </span>
                                    </div>
                                    <h3 style={{ fontSize: '18px', fontWeight: '600', marginBottom: '0.5rem' }}>
                                        {note.title}
                                    </h3>
                                    <p style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '1rem' }}>
                                        {note.description || 'No description'}
                                    </p>
                                    {note.group_name && (
                                        <div style={{ padding: '0.5rem', background: 'var(--secondary-bg)', borderRadius: '8px', marginBottom: '1rem' }}>
                                            <span style={{ fontSize: '12px', color: 'var(--text-secondary)' }}>
                                                📁 {note.group_name}
                                            </span>
                                        </div>
                                    )}
                                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                                        <button
                                            onClick={() => fetchNoteDetails(note.id)}
                                            disabled={loadingNoteDetails}
                                            className="btn btn-secondary"
                                            style={{ flex: 1, fontSize: '14px', padding: '0.5rem' }}
                                        >
                                            {loadingNoteDetails ? '⏳ Loading...' : '📖 Open'}
                                        </button>
                                        <button
                                            onClick={() => copyNote(note.id)}
                                            className="btn btn-primary"
                                            style={{ flex: 1, fontSize: '14px', padding: '0.5rem' }}
                                        >
                                            📋 Copy to My Notes
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            )}

            {/* Groups Tab */}
            {activeShareTab === 'groups' && (
                <div>
                    {/* Pending Invitations */}
                    {invitations.length > 0 && (
                        <div style={{ marginBottom: '2rem' }}>
                            <h3 style={{ fontSize: '16px', fontWeight: '600', marginBottom: '1rem' }}>
                                Pending Invitations ({invitations.length})
                            </h3>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
                                {invitations.map(inv => (
                                    <div key={inv.id} className="card" style={{ padding: '1rem', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                        <div>
                                            <strong style={{ fontSize: '15px' }}>{inv.group_name}</strong>
                                            <span style={{ fontSize: '13px', color: 'var(--text-secondary)', marginLeft: '0.5rem' }}>
                                                invited by {inv.invited_by_name}
                                            </span>
                                        </div>
                                        <div style={{ display: 'flex', gap: '0.5rem' }}>
                                            <button
                                                onClick={() => acceptInvitation(inv.id)}
                                                className="btn btn-primary"
                                                style={{ fontSize: '14px', padding: '0.5rem 1rem' }}
                                            >
                                                Accept
                                            </button>
                                            <button
                                                onClick={() => declineInvitation(inv.id)}
                                                className="btn btn-secondary"
                                                style={{ fontSize: '14px', padding: '0.5rem 1rem' }}
                                            >
                                                Decline
                                            </button>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}

                    {/* Groups List */}
                    {groups.length === 0 && invitations.length === 0 ? (
                        <div className="card" style={{ textAlign: 'center', padding: '3rem' }}>
                            <div style={{ fontSize: '48px', marginBottom: '1rem' }}>👥</div>
                            <h3 style={{ marginBottom: '0.5rem' }}>No groups yet</h3>
                            <p style={{ color: 'var(--text-secondary)', marginBottom: '1.5rem' }}>
                                Create a group to collaborate with others
                            </p>
                            <button onClick={() => setShowGroupModal(true)} className="btn btn-primary">
                                Create Your First Group
                            </button>
                        </div>
                    ) : (
                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '1rem' }}>
                            {groups.map(group => (
                                <div key={group.id} className="card" style={{ padding: '1.5rem' }}>
                                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: '1rem' }}>
                                        <div>
                                            <h3 style={{ fontSize: '18px', fontWeight: '600', marginBottom: '0.25rem' }}>
                                                {group.name}
                                            </h3>
                                            <span style={{
                                                fontSize: '11px',
                                                padding: '0.25rem 0.5rem',
                                                background: group.role === 'owner' ? 'var(--primary-light)' : 'var(--secondary-bg)',
                                                color: group.role === 'owner' ? 'var(--primary)' : 'var(--text-secondary)',
                                                borderRadius: '8px'
                                            }}>
                                                {group.role}
                                            </span>
                                        </div>
                                    </div>
                                    <p style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '1rem' }}>
                                        {group.description || 'No description'}
                                    </p>
                                    <div style={{ fontSize: '13px', color: 'var(--text-tertiary)', marginBottom: '1rem' }}>
                                        👥 {group.member_count} member{group.member_count !== 1 ? 's' : ''}
                                    </div>
                                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                                        <button
                                            onClick={() => {
                                                if (setActionParams) {
                                                    setActionParams({ groupId: group.id });
                                                    setActiveTab('notes');
                                                }
                                            }}
                                            className="btn btn-secondary"
                                            style={{ flex: 1, fontSize: '14px', padding: '0.5rem' }}
                                        >
                                            Open
                                        </button>
                                        {(group.role === 'owner' || group.role === 'admin') && (
                                            <button
                                                onClick={() => {
                                                    setSelectedGroup(group);
                                                    setShowInviteModal(true);
                                                }}
                                                className="btn btn-primary"
                                                style={{ flex: 1, fontSize: '14px', padding: '0.5rem' }}
                                            >
                                                Invite
                                            </button>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            )}

            {/* Find People Tab */}
            {activeShareTab === 'find-people' && (
                <UserSearch token={token} />
            )}

            {/* Share Modal */}
            {showShareModal && selectedNote && (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    background: 'rgba(0,0,0,0.5)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 1000
                }}>
                    <div className="card" style={{ width: '90%', maxWidth: '500px', padding: '2rem' }}>
                        <h3 style={{ marginBottom: '1rem' }}>Share: {selectedNote.title}</h3>
                        <p style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '1.5rem' }}>
                            Generate a shareable link for this note
                        </p>
                        <div style={{ marginBottom: '1.5rem' }}>
                            <label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '14px' }}>
                                Permission Level
                            </label>
                            <select
                                id="permission-select"
                                className="form-input"
                                defaultValue="view"
                                style={{ width: '100%', padding: '0.75rem', fontSize: '14px' }}
                            >
                                <option value="view">View Only</option>
                                <option value="comment">Can Comment</option>
                                <option value="edit">Can Edit</option>
                            </select>
                        </div>
                        <div style={{ display: 'flex', gap: '0.75rem' }}>
                            <button
                                onClick={() => {
                                    const permission = document.getElementById('permission-select').value;
                                    createShareLink(selectedNote.id, permission);
                                }}
                                className="btn btn-primary"
                                style={{ flex: 1 }}
                            >
                                Generate & Copy Link
                            </button>
                            <button
                                onClick={() => setShowShareModal(false)}
                                className="btn btn-secondary"
                            >
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Group Creation Modal */}
            {showGroupModal && (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    background: 'rgba(0,0,0,0.5)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 1000
                }}>
                    <div className="card" style={{ width: '90%', maxWidth: '500px', padding: '2rem' }}>
                        <h3 style={{ marginBottom: '1.5rem' }}>Create New Group</h3>
                        <form onSubmit={createGroup}>
                            <div style={{ marginBottom: '1rem' }}>
                                <label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '14px', fontWeight: '500' }}>
                                    Group Name *
                                </label>
                                <input
                                    name="groupName"
                                    type="text"
                                    required
                                    placeholder="e.g., Study Group 2024"
                                    className="form-input"
                                    style={{ width: '100%', padding: '0.75rem', fontSize: '14px' }}
                                />
                            </div>
                            <div style={{ marginBottom: '1rem' }}>
                                <label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '14px', fontWeight: '500' }}>
                                    Description
                                </label>
                                <textarea
                                    name="groupDescription"
                                    placeholder="What's this group about?"
                                    className="form-input"
                                    style={{ width: '100%', padding: '0.75rem', fontSize: '14px', minHeight: '80px', resize: 'vertical' }}
                                />
                            </div>
                            <div style={{ marginBottom: '1.5rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                                <input
                                    type="checkbox"
                                    name="isPrivate"
                                    id="isPrivate"
                                    style={{ width: '18px', height: '18px', cursor: 'pointer' }}
                                />
                                <label htmlFor="isPrivate" style={{ fontSize: '14px', cursor: 'pointer' }}>
                                    Make this group private
                                </label>
                            </div>
                            <div style={{ display: 'flex', gap: '0.75rem' }}>
                                <button
                                    type="submit"
                                    className="btn btn-primary"
                                    style={{ flex: 1 }}
                                >
                                    Create Group
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setShowGroupModal(false)}
                                    className="btn btn-secondary"
                                >
                                    Cancel
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Invite Members Modal */}
            {showInviteModal && selectedGroup && (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    background: 'rgba(0,0,0,0.5)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 1000
                }}>
                    <div className="card" style={{ width: '90%', maxWidth: '500px', padding: '2rem' }}>
                        <h3 style={{ marginBottom: '0.5rem' }}>Invite to {selectedGroup.name}</h3>
                        <p style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '1.5rem' }}>
                            Enter email addresses separated by commas
                        </p>
                        <form onSubmit={inviteMembers}>
                            <div style={{ marginBottom: '1.5rem' }}>
                                <label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '14px', fontWeight: '500' }}>
                                    Email Addresses *
                                </label>
                                <textarea
                                    name="emails"
                                    required
                                    placeholder="email1@example.com, email2@example.com"
                                    className="form-input"
                                    style={{ width: '100%', padding: '0.75rem', fontSize: '14px', minHeight: '100px', resize: 'vertical' }}
                                />
                                <span style={{ fontSize: '12px', color: 'var(--text-tertiary)', marginTop: '0.25rem', display: 'block' }}>
                                    Invitations will be sent via email
                                </span>
                            </div>
                            <div style={{ display: 'flex', gap: '0.75rem' }}>
                                <button
                                    type="submit"
                                    className="btn btn-primary"
                                    style={{ flex: 1 }}
                                >
                                    Send Invitations
                                </button>
                                <button
                                    type="button"
                                    onClick={() => {
                                        setShowInviteModal(false);
                                        setSelectedGroup(null);
                                    }}
                                    className="btn btn-secondary"
                                >
                                    Cancel
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Multi-Step Share Modal */}
            {showShareModal && (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    background: 'rgba(0,0,0,0.6)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 1000,
                    padding: '1rem'
                }} onClick={() => setShowShareModal(false)}>
                    <div className="card" style={{
                        width: '90%',
                        maxWidth: '700px',
                        maxHeight: '80vh',
                        display: 'flex',
                        flexDirection: 'column',
                        padding: 0,
                        overflow: 'hidden'
                    }} onClick={(e) => e.stopPropagation()}>

                        {/* Modal Header */}
                        <div style={{
                            padding: '1.5rem',
                            borderBottom: '2px solid var(--border-color)',
                            background: 'var(--bg-secondary)'
                        }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.75rem' }}>
                                <h2 style={{ fontSize: '20px', fontWeight: '700', margin: 0 }}>
                                    {shareModalStep === 1 ? '📝 Select Notes to Share' : '👥 Choose Recipients'}
                                </h2>
                                <button
                                    onClick={() => setShowShareModal(false)}
                                    style={{
                                        background: 'none',
                                        border: 'none',
                                        fontSize: '24px',
                                        cursor: 'pointer',
                                        color: 'var(--text-secondary)',
                                        padding: '0.25rem'
                                    }}
                                >
                                    ×
                                </button>
                            </div>

                            {/* Step Indicator */}
                            <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
                                <div style={{
                                    flex: 1,
                                    height: '4px',
                                    background: shareModalStep >= 1 ? 'var(--primary)' : 'var(--border-color)',
                                    borderRadius: '2px',
                                    transition: 'background 0.3s'
                                }}></div>
                                <div style={{
                                    flex: 1,
                                    height: '4px',
                                    background: shareModalStep >= 2 ? 'var(--primary)' : 'var(--border-color)',
                                    borderRadius: '2px',
                                    transition: 'background 0.3s'
                                }}></div>
                            </div>
                            <p style={{ fontSize: '12px', color: 'var(--text-secondary)', marginTop: '0.5rem', textAlign: 'center' }}>
                                Step {shareModalStep} of 2
                            </p>
                        </div>

                        {/* Modal Body */}
                        <div style={{ flex: 1, overflow: 'auto', padding: '1.5rem' }}>
                            {shareModalStep === 1 ? (
                                /* Step 1: Select Notes */
                                <div>
                                    {/* Search Bar */}
                                    <div style={{ marginBottom: '1rem' }}>
                                        <input
                                            type="text"
                                            placeholder="🔍 Search notes by title, subject, or tags..."
                                            value={noteSearchQuery}
                                            onChange={(e) => setNoteSearchQuery(e.target.value)}
                                            className="form-input"
                                            style={{
                                                width: '100%',
                                                padding: '0.75rem',
                                                fontSize: '14px',
                                                border: '2px solid var(--border-color)',
                                                borderRadius: '8px'
                                            }}
                                        />
                                    </div>

                                    {loadingNotes ? (
                                        <div style={{ textAlign: 'center', padding: '3rem' }}>
                                            <div style={{ fontSize: '48px', marginBottom: '1rem' }}>⏳</div>
                                            <p style={{ color: 'var(--text-secondary)' }}>Loading your notes...</p>
                                        </div>
                                    ) : filteredNotes.length === 0 ? (
                                        <div style={{ textAlign: 'center', padding: '3rem', background: 'var(--bg-secondary)', borderRadius: '8px' }}>
                                            <div style={{ fontSize: '48px', marginBottom: '1rem' }}>📭</div>
                                            <p style={{ color: 'var(--text-secondary)' }}>
                                                {noteSearchQuery ? 'No notes match your search' : 'No notes found'}
                                            </p>
                                        </div>
                                    ) : (
                                        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
                                            {filteredNotes.map(note => (
                                                <label
                                                    key={note.id}
                                                    style={{
                                                        display: 'flex',
                                                        alignItems: 'start',
                                                        gap: '1rem',
                                                        padding: '1rem',
                                                        background: selectedNotes.includes(note.id) ? 'var(--primary-light)' : 'var(--bg-secondary)',
                                                        border: selectedNotes.includes(note.id) ? '2px solid var(--primary)' : '2px solid transparent',
                                                        borderRadius: '8px',
                                                        cursor: 'pointer',
                                                        transition: 'all 0.2s'
                                                    }}
                                                >
                                                    <input
                                                        type="checkbox"
                                                        checked={selectedNotes.includes(note.id)}
                                                        onChange={() => toggleNoteSelection(note.id)}
                                                        style={{
                                                            width: '20px',
                                                            height: '20px',
                                                            cursor: 'pointer',
                                                            marginTop: '0.25rem'
                                                        }}
                                                    />
                                                    <div style={{ flex: 1 }}>
                                                        <h4 style={{ fontSize: '15px', fontWeight: '600', marginBottom: '0.25rem' }}>
                                                            {note.title}
                                                        </h4>
                                                        {note.subject && (
                                                            <span style={{
                                                                display: 'inline-block',
                                                                padding: '0.125rem 0.5rem',
                                                                background: 'var(--primary)',
                                                                color: 'white',
                                                                borderRadius: '10px',
                                                                fontSize: '11px',
                                                                fontWeight: '500',
                                                                marginBottom: '0.25rem'
                                                            }}>
                                                                {note.subject}
                                                            </span>
                                                        )}
                                                        <p style={{ fontSize: '12px', color: 'var(--text-secondary)', margin: 0 }}>
                                                            {note.created_at && new Date(note.created_at).toLocaleDateString()}
                                                        </p>
                                                    </div>
                                                </label>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            ) : (
                                /* Step 2: Select Friends & Permission */
                                <div>
                                    {/* Permission Selector */}
                                    <div style={{ marginBottom: '1.5rem' }}>
                                        <label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '14px', fontWeight: '600' }}>
                                            Permission Level
                                        </label>
                                        <select
                                            value={sharePermission}
                                            onChange={(e) => setSharePermission(e.target.value)}
                                            className="form-input"
                                            style={{
                                                width: '100%',
                                                padding: '0.75rem',
                                                fontSize: '14px',
                                                border: '2px solid var(--border-color)',
                                                borderRadius: '8px'
                                            }}
                                        >
                                            <option value="view">👁️ View Only</option>
                                            <option value="comment">💬 Can Comment</option>
                                            <option value="edit">✏️ Can Edit</option>
                                        </select>
                                    </div>

                                    {/* Friends List */}
                                    <div>
                                        <label style={{ display: 'block', marginBottom: '0.75rem', fontSize: '14px', fontWeight: '600' }}>
                                            Select Friends ({friends.length} available)
                                        </label>
                                        {friends.length === 0 ? (
                                            <div style={{ textAlign: 'center', padding: '3rem', background: 'var(--bg-secondary)', borderRadius: '8px' }}>
                                                <div style={{ fontSize: '48px', marginBottom: '1rem' }}>👥</div>
                                                <p style={{ color: 'var(--text-secondary)', marginBottom: '0.5rem' }}>No friends yet</p>
                                                <p style={{ fontSize: '12px', color: 'var(--text-tertiary)' }}>
                                                    Go to Find People to add friends
                                                </p>
                                            </div>
                                        ) : (
                                            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem', maxHeight: '300px', overflow: 'auto' }}>
                                                {friends.map(friend => (
                                                    <label
                                                        key={friend.id}
                                                        style={{
                                                            display: 'flex',
                                                            alignItems: 'center',
                                                            gap: '1rem',
                                                            padding: '1rem',
                                                            background: selectedFriends.includes(friend.id) ? 'var(--primary-light)' : 'var(--bg-secondary)',
                                                            border: selectedFriends.includes(friend.id) ? '2px solid var(--primary)' : '2px solid transparent',
                                                            borderRadius: '8px',
                                                            cursor: 'pointer',
                                                            transition: 'all 0.2s'
                                                        }}
                                                    >
                                                        <input
                                                            type="checkbox"
                                                            checked={selectedFriends.includes(friend.id)}
                                                            onChange={() => toggleFriendSelection(friend.id)}
                                                            style={{
                                                                width: '20px',
                                                                height: '20px',
                                                                cursor: 'pointer'
                                                            }}
                                                        />
                                                        <div style={{
                                                            width: '40px',
                                                            height: '40px',
                                                            borderRadius: '50%',
                                                            background: friend.photo_url ? `url(${friend.photo_url})` : 'var(--primary)',
                                                            backgroundSize: 'cover',
                                                            backgroundPosition: 'center',
                                                            display: 'flex',
                                                            alignItems: 'center',
                                                            justifyContent: 'center',
                                                            color: 'white',
                                                            fontWeight: '600',
                                                            fontSize: '16px'
                                                        }}>
                                                            {!friend.photo_url && (friend.name?.charAt(0).toUpperCase() || '?')}
                                                        </div>
                                                        <div>
                                                            <div style={{ fontWeight: '600', fontSize: '14px' }}>{friend.name}</div>
                                                            <div style={{ fontSize: '12px', color: 'var(--text-secondary)' }}>
                                                                {friend.username ? `@${friend.username}` : `NV-${friend.share_code}`}
                                                            </div>
                                                        </div>
                                                    </label>
                                                ))}
                                            </div>
                                        )}
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Modal Footer */}
                        <div style={{
                            padding: '1rem 1.5rem',
                            borderTop: '2px solid var(--border-color)',
                            display: 'flex',
                            justifyContent: 'space-between',
                            alignItems: 'center',
                            background: 'var(--bg-secondary)'
                        }}>
                            <div style={{ fontSize: '13px', color: 'var(--text-secondary)' }}>
                                {shareModalStep === 1 ? (
                                    <span>{selectedNotes.length} note{selectedNotes.length !== 1 ? 's' : ''} selected</span>
                                ) : (
                                    <span>{selectedFriends.length} friend{selectedFriends.length !== 1 ? 's' : ''} selected</span>
                                )}
                            </div>
                            <div style={{ display: 'flex', gap: '0.75rem' }}>
                                {shareModalStep === 2 && (
                                    <button
                                        onClick={() => setShareModalStep(1)}
                                        className="btn btn-secondary"
                                    >
                                        ← Back
                                    </button>
                                )}
                                {shareModalStep === 1 ? (
                                    <button
                                        onClick={() => setShareModalStep(2)}
                                        disabled={selectedNotes.length === 0}
                                        className="btn btn-primary"
                                        style={{
                                            opacity: selectedNotes.length === 0 ? 0.5 : 1,
                                            cursor: selectedNotes.length === 0 ? 'not-allowed' : 'pointer'
                                        }}
                                    >
                                        Next →
                                    </button>
                                ) : (
                                    <button
                                        onClick={submitShare}
                                        disabled={sharingInProgress || selectedFriends.length === 0}
                                        className="btn btn-primary"
                                        style={{
                                            opacity: (sharingInProgress || selectedFriends.length === 0) ? 0.5 : 1,
                                            cursor: (sharingInProgress || selectedFriends.length === 0) ? 'not-allowed' : 'pointer'
                                        }}
                                    >
                                        {sharingInProgress ? '⏳ Sharing...' : '✨ Share Notes'}
                                    </button>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* View Shared Note Modal */}
            {showViewNoteModal && viewingNote && (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    background: 'rgba(0,0,0,0.6)',
                    backdropFilter: 'blur(4px)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 2000,
                    padding: '20px'
                }} onClick={() => {
                    setShowViewNoteModal(false);
                    setViewingNote(null);
                    setViewingNoteDetails(null);
                }}>
                    <div style={{
                        background: 'var(--bg-primary)',
                        borderRadius: '1rem',
                        width: '100%',
                        maxWidth: '900px',
                        maxHeight: '90vh',
                        overflow: 'hidden',
                        display: 'flex',
                        flexDirection: 'column',
                        boxShadow: '0 20px 60px rgba(0,0,0,0.3)'
                    }} onClick={(e) => e.stopPropagation()}>

                        {/* Scrollable content area */}
                        <div style={{ overflow: 'auto', padding: '2rem' }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
                                <h2 style={{ margin: 0 }}>{viewingNote.title}</h2>
                                <button
                                    onClick={() => setShowViewNoteModal(false)}
                                    className="btn-icon"
                                    style={{ fontSize: '24px', background: 'none', border: 'none', cursor: 'pointer' }}
                                >
                                    ×
                                </button>
                            </div>

                            {/* Note Metadata */}
                            <div style={{ marginBottom: '1.5rem', padding: '1rem', background: 'var(--secondary-bg)', borderRadius: '8px' }}>
                                <div style={{ display: 'flex', gap: '2rem', flexWrap: 'wrap', fontSize: '14px' }}>
                                    <div>
                                        <strong>Shared by:</strong> {viewingNote.owner_name || 'Unknown'}
                                    </div>
                                    <div>
                                        <strong>Permission:</strong> {viewingNote.permission_level || 'view'}
                                    </div>
                                    {viewingNote.shared_at && (
                                        <div>
                                            <strong>Shared:</strong> {new Date(viewingNote.shared_at).toLocaleDateString()}
                                        </div>
                                    )}
                                </div>
                            </div>

                            {/* Note Content */}
                            <div style={{ marginBottom: '1.5rem' }}>
                                <h3 style={{ fontSize: '16px', marginBottom: '0.75rem' }}>Content</h3>
                                {viewingNoteDetails && viewingNoteDetails.content_blocks && viewingNoteDetails.content_blocks.length > 0 ? (
                                    <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                                        {viewingNoteDetails.content_blocks.map((block, index) => (
                                            <div key={block.id} style={{
                                                padding: '1rem',
                                                background: 'var(--bg-secondary)',
                                                borderRadius: '8px',
                                                border: '1px solid var(--border-color)'
                                            }}>
                                                {block.content_type === 'text' && (
                                                    <div style={{ whiteSpace: 'pre-wrap', fontSize: '14px', lineHeight: '1.6' }}>
                                                        {block.content_data?.text || block.extracted_text || 'No text content'}
                                                    </div>
                                                )}
                                                {block.content_type === 'image' && (
                                                    <div style={{ textAlign: 'center' }}>
                                                        <img
                                                            src={`${API_URL.replace('/api', '')}/uploads/${block.file_path}`}
                                                            alt="Note content"
                                                            style={{ maxWidth: '100%', borderRadius: '6px', display: 'block', margin: '0 auto' }}
                                                        />
                                                        {block.extracted_text && (
                                                            <p style={{ marginTop: '0.75rem', fontSize: '13px', color: 'var(--text-secondary)', textAlign: 'left' }}>
                                                                <strong>Extracted text:</strong> {block.extracted_text}
                                                            </p>
                                                        )}
                                                    </div>
                                                )}
                                                {block.content_type === 'pdf' && (
                                                    <div>
                                                        <div style={{ textAlign: 'center', padding: '1rem' }}>
                                                            <span style={{ fontSize: '48px' }}>📄</span>
                                                            <p style={{ marginTop: '0.5rem', fontSize: '14px', fontWeight: '600' }}>{block.filename || 'PDF Document'}</p>
                                                            <a
                                                                href={`${API_URL.replace('/api', '')}/uploads/${block.file_path}`}
                                                                target="_blank"
                                                                rel="noopener noreferrer"
                                                                style={{ color: 'var(--primary)', fontSize: '13px', textDecoration: 'underline' }}
                                                            >
                                                                Open PDF
                                                            </a>
                                                        </div>
                                                        {block.extracted_text && (
                                                            <div style={{ marginTop: '1rem', padding: '0.75rem', background: 'var(--bg-primary)', borderRadius: '6px' }}>
                                                                <p style={{ fontSize: '12px', color: 'var(--text-tertiary)', marginBottom: '0.5rem' }}>Extracted Text Preview:</p>
                                                                <div style={{ fontSize: '13px', color: 'var(--text-secondary)', maxHeight: '150px', overflow: 'auto' }}>
                                                                    {block.extracted_text.substring(0, 500)}{block.extracted_text.length > 500 ? '...' : ''}
                                                                </div>
                                                            </div>
                                                        )}
                                                    </div>
                                                )}
                                                {block.content_type === 'audio' && (
                                                    <div>
                                                        <div style={{ marginBottom: '0.75rem' }}>
                                                            <span style={{ fontSize: '24px', marginRight: '0.5rem' }}>🎵</span>
                                                            <span style={{ fontSize: '14px', fontWeight: '600' }}>{block.filename || 'Audio Recording'}</span>
                                                        </div>
                                                        <audio controls style={{ width: '100%', marginBottom: '0.75rem' }}>
                                                            <source src={`${API_URL.replace('/api', '')}/uploads/${block.file_path}`} />
                                                            Your browser does not support audio playback.
                                                        </audio>
                                                        {block.extracted_text && (
                                                            <div style={{ padding: '0.75rem', background: 'var(--bg-primary)', borderRadius: '6px' }}>
                                                                <p style={{ fontSize: '12px', color: 'var(--text-tertiary)', marginBottom: '0.5rem' }}>Transcription:</p>
                                                                <p style={{ fontSize: '13px', fontStyle: 'italic', color: 'var(--text-secondary)' }}>
                                                                    {block.extracted_text}
                                                                </p>
                                                            </div>
                                                        )}
                                                    </div>
                                                )}
                                                {block.content_type === 'link' && (
                                                    <div>
                                                        <span style={{ fontSize: '20px', marginRight: '0.5rem' }}>🔗</span>
                                                        <a
                                                            href={block.content_data?.url}
                                                            target="_blank"
                                                            rel="noopener noreferrer"
                                                            style={{ color: 'var(--primary)', textDecoration: 'underline', fontSize: '14px', wordBreak: 'break-all' }}
                                                        >
                                                            {block.content_data?.url}
                                                        </a>
                                                    </div>
                                                )}
                                            </div>
                                        ))}
                                    </div>
                                ) : (
                                    <div style={{ padding: '2rem', textAlign: 'center', background: 'var(--bg-secondary)', borderRadius: '8px' }}>
                                        <p style={{ fontSize: '14px', color: 'var(--text-secondary)' }}>
                                            {loadingNoteDetails ? '⏳ Loading content...' : 'No content blocks found'}
                                        </p>
                                    </div>
                                )}
                            </div>

                            {/* Actions */}
                            <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
                                <button
                                    onClick={() => {
                                        copyNote(viewingNote.id);
                                        setShowViewNoteModal(false);
                                    }}
                                    className="btn btn-primary"
                                >
                                    📋 Copy to My Notes
                                </button >
                                <button
                                    onClick={() => setShowViewNoteModal(false)}
                                    className="btn btn-secondary"
                                >
                                    Close
                                </button>
                            </div >
                        </div >
                    </div >
                </div >
            )}
        </div >
    );
}

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