let offset = 0; // Track the current offset for pagination
const limit = 10; // Number of posts per request
let isLoading = false; // Prevent multiple simultaneous API calls

function getProfileUserId() {
    const profileInput = document.getElementById('profileUserId');
    if (!profileInput) {
        return null;
    }
    const parsed = parseInt(profileInput.value, 10);
    return Number.isNaN(parsed) ? null : parsed;
}

// Format timestamp as relative time (e.g., "2 hours ago")
function formatTimeAgo(timestamp) {
    const now = new Date();
    const date = new Date(timestamp);
    const secondsAgo = Math.floor((now - date) / 1000);
    
    if (secondsAgo < 60) {
        return 'Just now';
    }
    
    const minutesAgo = Math.floor(secondsAgo / 60);
    if (minutesAgo < 60) {
        return `${minutesAgo} ${minutesAgo === 1 ? 'minute' : 'minutes'} ago`;
    }
    
    const hoursAgo = Math.floor(minutesAgo / 60);
    if (hoursAgo < 24) {
        return `${hoursAgo} ${hoursAgo === 1 ? 'hour' : 'hours'} ago`;
    }
    
    const daysAgo = Math.floor(hoursAgo / 24);
    if (daysAgo < 30) {
        return `${daysAgo} ${daysAgo === 1 ? 'day' : 'days'} ago`;
    }
    
    const monthsAgo = Math.floor(daysAgo / 30);
    if (monthsAgo < 12) {
        return `${monthsAgo} ${monthsAgo === 1 ? 'month' : 'months'} ago`;
    }
    
    const yearsAgo = Math.floor(monthsAgo / 12);
    return `${yearsAgo} ${yearsAgo === 1 ? 'year' : 'years'} ago`;
}

// Tip Modal and actions
function openTipModal(postId, authorId) {
    const modalId = `tipModal-${postId}`;
    if (!document.getElementById(modalId)) {
        const html = `
        <div class="modal fade" id="${modalId}" tabindex="-1" aria-hidden="true">
          <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">Send a Tip</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
              </div>
              <div class="modal-body">
                <div class="mb-3">
                  <label class="form-label">Amount</label>
                  <div class="input-group">
                    <span class="input-group-text">$</span>
                    <input type="number" class="form-control" id="tip-amount-${postId}" min="0.1" step="0.1" value="1.0" />
                  </div>
                  <div class="form-text">Funds will be deducted from your wallet.</div>
                </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" onclick="sendTip(${postId})">Send Tip</button>
              </div>
            </div>
          </div>
        </div>`;
        document.body.insertAdjacentHTML('beforeend', html);
    }
    new bootstrap.Modal(document.getElementById(modalId)).show();
}

async function sendTip(postId) {
    const amount = parseFloat(document.getElementById(`tip-amount-${postId}`).value || '0');
    if (isNaN(amount) || amount <= 0) {
        showAlert('warning', 'Invalid Amount', 'Please enter a valid tip amount.');
        return;
    }
    try {
        const resp = await axios.post(base_url + '/webapi/post/action', {
            post_id: postId,
            action: 'tip',
            amount: amount,
        });
        if (resp.data && resp.data.status === 200) {
            showAlert('success', 'Thank you!', 'Your tip was sent successfully.');
            bootstrap.Modal.getInstance(document.getElementById(`tipModal-${postId}`)).hide();
        } else {
            showAlert('error', 'Tip Failed', resp.data && resp.data.message ? resp.data.message : 'Could not send tip.');
        }
    } catch (e) {
        showAlert('error', 'Tip Failed', 'Could not send tip.');
    }
}

// Validate Schedule DateTime
function validateScheduleDateTime() {
    if (!isScheduled) return true;
    
    const selectedDateTime = $('.js_publisher-schedule-date').val();
    if (!selectedDateTime) {
        myAlert.fire({
            icon: 'error',
            title: 'Schedule Date Required',
            text: 'Please select a date and time for your scheduled post.'
        });
        return false;
    }
    
    const selectedDate = new Date(selectedDateTime);
    const now = new Date();
    
    if (selectedDate <= now) {
        myAlert.fire({
            icon: 'error',
            title: 'Invalid Schedule Time',
            text: 'Please select a future date and time for your scheduled post.'
        });
        return false;
    }
    
    scheduledDateTime = selectedDateTime;
    return true;
}

// HTML escape helper used by renderPost for colored posts
function escapeHtml(str) {
    if (!str) return '';
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

function renderPost(post) {
    let author = post.author;
    let postMedia = post.media || [];
    let avatar = (post.anonymous ? (base_url + '/assets/images/defaults/anonymous.png') : author.avatar);
    let postText = post.text ? post.text : "";
    let timeAgo = formatTimeAgo(post.dates.created);
    const currentUserId = window.user && typeof window.user.id !== 'undefined' ? parseInt(window.user.id, 10) : null;
    const authorId = author && typeof author.id !== 'undefined' ? parseInt(author.id, 10) : null;
    const isPostOwner = currentUserId !== null && authorId !== null && currentUserId === authorId;
    let feelingCategory = post.feeling.category ? post.feeling.category : "";
    let feelingDescription = post.feeling.description ? post.feeling.description : "";
    let feelingText = "";
    let feelingIcon = "";
    const authorFullName = author ? [author.first_name, author.last_name].filter(Boolean).join(' ').trim() : '';
    const authorNameFallback = author ? (author.name || author.username || 'User') : 'User';
    const authorName = post.anonymous ? 'Anonymous' : (authorFullName || authorNameFallback);
    const profileUrl = (!post.anonymous && authorId) ? `/profile/${authorId}` : 'javascript:void(0)';
    
    // Format feeling/activity display
    if(feelingCategory == "Feeling") {
        feelingIcon = `<i class="bi bi-heart-fill text-danger"></i>`;
    } else if(feelingCategory == "Traveling") {
        feelingIcon = `<i class="bi bi-map-fill text-success"></i>`;
    } else if(feelingCategory == "Watching") {
        feelingIcon = `<i class="bi bi-camera-reels text-info"></i>`;
    } else if(feelingCategory == "Listening") {
        feelingIcon = `<i class="bi bi-music-note text-primary"></i>`;
    }
    
    if(feelingCategory && feelingDescription) {
        feelingText = `<span class="ms-1 badge bg-light text-dark rounded-pill"> ${feelingIcon} ${feelingCategory} ${feelingDescription}</span>`;
    } else if(feelingCategory) {
        feelingText = `<span class="ms-1 badge bg-light text-dark rounded-pill"> ${feelingIcon} ${feelingCategory}</span>`;
    }
    
    // Build page/group context line
    let contextLine = '';
    try {
        if (post.associations && post.associations.page) {
            const p = post.associations.page;
            const title = escapeHtml((p && p.title) ? p.title : 'Page');
            contextLine = `<div class="small text-muted"><i class=\"bi bi-flag\"></i> Posted to page <strong>${title}</strong></div>`;
        } else if (post.associations && post.associations.group) {
            const g = post.associations.group;
            const name = escapeHtml((g && g.name) ? g.name : 'Group');
            contextLine = `<div class="small text-muted"><i class=\"bi bi-people\"></i> Posted in group <strong>${name}</strong></div>`;
        }
    } catch (e) { /* noop */ }

    // Handle location
    let postLocation = post.location ? showMap(post.location) : "";
    let locationBadge = post.location ? `<div class="mb-2"><i class="bi bi-geo-alt-fill text-danger"></i> <small class="text-muted">at ${post.location}</small></div>` : "";
    
    // Apply colored post styling when applicable
    if (post.background && (post.background.color || post.background.text_color || post.background.font_size)) {
        const bgColor = post.background.color || '';
        const txtColor = post.background.text_color || '';
        const fSize = post.background.font_size || 'normal';
        const fontPx = fSize === 'extra-large' ? 24 : (fSize === 'large' ? 20 : (fSize === 'small' ? 14 : 16));
        // Wrap post text with a styled container
        postText = `<div class="p-3 rounded-3" style="background-color:${bgColor};color:${txtColor};font-size:${fontPx}px;white-space:pre-line">${escapeHtml(postText)}</div>`;
    }
    // Handle poll posts
    let postType = post.post_type;
    let pollHtml = "";
    if(postType == 'poll' && post.poll) {
        postText = post.poll.title || postText;
        const voted = !!post.poll.voted;
        const myOptionId = post.poll.my_option_id || null;
        pollHtml = `
        <div class="poll-container bg-light p-3 rounded-3 mb-3" data-post-id="${post.id}">
            <div class="poll-question fw-bold mb-3">
               ${postText}
            </div>
            <div class="poll-options">
                ${post.poll.options ? post.poll.options.map((option, index) => {
                    const checked = myOptionId && myOptionId === option.id ? 'checked' : '';
                    const percentage = option.percentage || 0;
                    return `
                    <div class="poll-option mb-2">
                        <div class="form-check">
                            <input class="form-check-input poll-radio" type="radio" name="poll-${post.id}" id="poll-${post.id}-option-${option.id}" value="${option.id}" ${checked} ${voted ? '' : ''}>
                            <label class="form-check-label w-100" for="poll-${post.id}-option-${option.id}">
                                <div class="d-flex align-items-center">
                                    <span class="me-2">${option.text}</span>
                                    <div class="progress flex-grow-1" style="height: 8px;">
                                        <div class="progress-bar" role="progressbar" style="width: ${percentage}%" aria-valuenow="${percentage}" aria-valuemin="0" aria-valuemax="100"></div>
                                    </div>
                                    <span class="ms-2 small">${percentage}%</span>
                                </div>
                            </label>
                        </div>
                    </div>`;
                }).join('') : ''}
            </div>
            <div class="poll-footer mt-3 small text-muted">
                <i class="bi bi-people-fill"></i> <span class="poll-total-votes">${post.poll.total_votes || 0}</span> votes
            </div>
        </div>`;
    }
    
    // Get user's current reaction (if any)
    let userReaction = post.stats.my_reaction || null;
    let reactionText = 'Like';
    let reactionColor = '';
    let reactionIcon = 'reaction-like';

    if (userReaction === 1) {
        reactionText = 'Like';
        reactionColor = 'text-primary';
        reactionIcon = 'reaction-like';
    } else if (userReaction === 2) {
        reactionText = 'Love';
        reactionColor = 'text-danger';
        reactionIcon = 'reaction-love';
    } else if (userReaction === 3) {
        reactionText = 'Haha';
        reactionColor = 'text-warning';
        reactionIcon = 'reaction-laugh';
    } else if (userReaction === 4) {
        reactionText = 'Wow';
        reactionColor = 'text-info';
        reactionIcon = 'reaction-wow';
    } else if (userReaction === 5) {
        reactionText = 'Sad';
        reactionColor = 'text-secondary';
        reactionIcon = 'reaction-sad';
    } else if (userReaction === 6) {
        reactionText = 'Angry';
        reactionColor = 'text-warning';
        reactionIcon = 'reaction-angry';
    }
    
    // Create the comments status text
    let commentsStatus = !post.settings.comments_enabled ? 
        '<span class="text-muted fw-light">(Comments disabled)</span>' : 
        `<span>${post.stats.comments}</span>`;

    // Build media display: videos first (single), else images gallery, then audio, then files, then GIF (if any)
    let mediaHtml = '';
    if (postMedia.length > 0) {
        
        const videoMedia = postMedia.filter(m => m.type === 'video');
        const imageMedia = postMedia.filter(m => m.type === 'image');
        const audioMedia = postMedia.filter(m => m.type === 'audio');
        const fileMedia  = postMedia.filter(m => !['image','video','audio'].includes(m.type));

        // If there's exactly one video, render a responsive HTML5 player
        if (videoMedia.length === 1 && imageMedia.length === 0) {
            const v = videoMedia[0];
            mediaHtml = `
            <div class="mb-3 rounded-3 overflow-hidden" style="aspect-ratio:16/9">
                <video class="w-100 h-100" style="object-fit:cover" preload="metadata" controls crossorigin playsinline>
                    <source src="${v.url}" type="video/mp4">
                    Your browser does not support the video tag.
                </video>
            </div>`;
        } else if (videoMedia.length > 0 && imageMedia.length > 0) {
            // If both exist, show video first, then images below
            const v = videoMedia[0];
            mediaHtml = `
            <div class="mb-3 rounded-3 overflow-hidden" style="aspect-ratio:16/9">
                <video class="w-100 h-100" style="object-fit:cover" preload="metadata" controls crossorigin playsinline>
                    <source src="${v.url}" type="video/mp4">
                </video>
            </div>`;
            // Then append images gallery (continues below)
        }
        if (imageMedia.length) {
            // Helper to build a single tile with aspect-ratio and optional overlay
            const buildTile = (url, alt, ratio = '1/1', overlayHtml = '') => `
                <div class="position-relative rounded overflow-hidden" style="aspect-ratio:${ratio}">
                    <img class="position-absolute top-0 start-0 w-100 h-100 object-fit-cover" src="${url}" alt="${alt}" loading="lazy" decoding="async" onclick="openImageViewer('${url}')">
                    ${overlayHtml}
                </div>`;

            const n = imageMedia.length;
            if (n === 1) {
                const url = imageMedia[0].url;
                mediaHtml = `
                <div class="mb-3">
                    ${buildTile(url, 'Post Image', '16/9', `
                        <button class="btn btn-light btn-sm rounded-circle position-absolute" style="top:10px; right:10px; z-index:2" onclick="openImageViewer('${url}')">
                            <i class="bi bi-arrows-fullscreen"></i>
                        </button>
                    `)}
                </div>`;
            } else if (n === 2) {
                mediaHtml = `
                <div class="mb-3">
                    <div class="row g-2">
                        <div class="col-6">${buildTile(imageMedia[0].url, 'Post Image 1', '4/5')}</div>
                        <div class="col-6">${buildTile(imageMedia[1].url, 'Post Image 2', '4/5')}</div>
                    </div>
                </div>`;
            } else if (n === 3) {
                mediaHtml = `
                <div class="mb-3">
                    <div class="row g-2">
                        <div class="col-12 col-md-7">${buildTile(imageMedia[0].url, 'Post Image 1', '4/5')}</div>
                        <div class="col-12 col-md-5">
                            <div class="d-flex flex-column gap-2"> 
                                ${buildTile(imageMedia[1].url, 'Post Image 2', '1/1')}
                                ${buildTile(imageMedia[2].url, 'Post Image 3', '1/1')}
                            </div>
                        </div>
                    </div>
                </div>`;
            } else if (n === 4) {
                mediaHtml = `
                <div class="mb-3">
                    <div class="row g-2">
                        <div class="col-6">${buildTile(imageMedia[0].url, 'Post Image 1', '1/1')}</div>
                        <div class="col-6">${buildTile(imageMedia[1].url, 'Post Image 2', '1/1')}</div>
                        <div class="col-6">${buildTile(imageMedia[2].url, 'Post Image 3', '1/1')}</div>
                        <div class="col-6">${buildTile(imageMedia[3].url, 'Post Image 4', '1/1')}</div>
                    </div>
                </div>`;
            } else {
                // 5 or more images: mosaic (1 tall + two stacked + bottom row with overlay on last)
                const remaining = n - 5;
                const overlay = remaining > 0 ? `
                    <div class="position-absolute top-0 start-0 w-100 h-100 bg-dark bg-opacity-50 d-flex justify-content-center align-items-center">
                        <span class="text-white fs-3 fw-bold">+${remaining}</span>
                    </div>` : '';

                mediaHtml = `
                <div class="mb-3">
                    <div class="row g-2">
                        <div class="col-12 col-md-7">${buildTile(imageMedia[0].url, 'Post Image 1', '4/5')}</div>
                        <div class="col-12 col-md-5">
                            <div class="d-flex flex-column gap-2">
                                ${buildTile(imageMedia[1].url, 'Post Image 2', '1/1')}
                                ${buildTile(imageMedia[2].url, 'Post Image 3', '1/1')}
                            </div>
                        </div>
                        <div class="col-6">${buildTile(imageMedia[3].url, 'Post Image 4', '1/1')}</div>
                        <div class="col-6">${buildTile(imageMedia[4].url, 'Post Image 5', '1/1', overlay)}</div>
                    </div>
                </div>`;
            }
        }

        // Append audio players (compact cards)
        if (audioMedia.length) {
            const buildAudio = (a) => `
            <div class="mb-3 p-3 rounded-3 border d-flex align-items-center gap-3 bg-light-subtle">
                <div class="flex-shrink-0 rounded-circle bg-primary d-flex align-items-center justify-content-center" style="width:44px;height:44px;">
                    <i class="bi bi-mic-fill text-white"></i>
                </div>
                <div class="flex-grow-1">
                    <div class="small text-muted">${a.original_name}</div>
                    <audio controls crossorigin playsinline preload="metadata" class="w-100">
                        <source src="${a.url}" type="audio/mpeg">
                        <source src="${a.url}" type="audio/wav">
                        Your browser does not support the audio element.
                    </audio>
                </div>
            </div>`;
            mediaHtml += audioMedia.map(buildAudio).join('');
        }

        // Append generic files (documents, archives, etc.)
        if (fileMedia.length) {
            const fileIcon = (mime) => {
                if (!mime) return 'bi-file-earmark';
                if (mime.includes('pdf')) return 'bi-file-earmark-pdf text-danger';
                if (mime.includes('zip') || mime.includes('rar') || mime.includes('7z')) return 'bi-file-earmark-zip text-warning';
                if (mime.includes('word') || mime.includes('msword')) return 'bi-file-earmark-word text-primary';
                if (mime.includes('excel') || mime.includes('spreadsheet')) return 'bi-file-earmark-excel text-success';
                if (mime.includes('text')) return 'bi-file-earmark-text';
                return 'bi-file-earmark';
            };
            const humanSize = (bytes) => {
                const b = Number(bytes || 0);
                if (!b) return '';
                const u = ['B','KB','MB','GB'];
                const i = Math.floor(Math.log(b)/Math.log(1024));
                return `${(b/Math.pow(1024,i)).toFixed(1)} ${u[i]}`;
            };
            const buildFile = (f) => `
            <a class="text-decoration-none" href="${f.url}" target="_blank" rel="noopener noreferrer">
                <div class="mb-3 p-3 rounded-3 border d-flex align-items-center gap-3 bg-white">
                    <div class="flex-shrink-0 d-flex align-items-center justify-content-center" style="width:44px;height:44px;">
                        <i class="bi ${fileIcon(f.mime_type)} fs-3"></i>
                    </div>
                    <div class="flex-grow-1 overflow-hidden">
                        <div class="fw-semibold text-truncate">${escapeHtml(f.original_name || 'Attachment')}</div>
                        <div class="small text-muted">${escapeHtml(f.mime_type || '')} ${humanSize(f.size) ? '· ' + humanSize(f.size) : ''}</div>
                    </div>
                    <div class="flex-shrink-0">
                        <i class="bi bi-box-arrow-up-right"></i>
                    </div>
                </div>
            </a>`;
            mediaHtml += fileMedia.map(buildFile).join('');
        }
    }

    // Append GIF if present
    if (post.gif && post.gif.url) {
        // Sanitize by forcing https and rel noopener on wrapper link (if any)
        const gifUrl = String(post.gif.url).replace(/^http:\/\//, 'https://');
        const gifTitle = post.gif.title ? escapeHtml(post.gif.title) : 'GIF';
        mediaHtml += `
        <div class="mb-3 rounded-3 overflow-hidden">
            <img src="${gifUrl}" alt="${gifTitle}" class="w-100 rounded-3" loading="lazy" decoding="async" referrerpolicy="no-referrer" />
        </div>`;
    }

    // Special sections: Event and Product
    let specialSectionHtml = '';
    if (postType === 'event' && post.event_details) {
        const e = post.event_details;
        const whenText = `${formatEventDate(e.start_date)}${e.start_time ? ' · ' + e.start_time : ''}`;
        const cover = e.cover_image ? `<img class="img-fluid w-100 rounded-3 mb-2" src="${e.cover_image}" alt="Event Cover">` : '';
        specialSectionHtml = `
        <div class="border rounded-3 p-3 mb-3 bg-light">
            <div class="d-flex align-items-center mb-2">
                <span class="badge bg-primary me-2"><i class="bi bi-calendar-event"></i> Event</span>
                <h5 class="mb-0">${e.name || ''}</h5>
            </div>
            ${cover}
            <div class="small text-muted mb-2">
                ${e.location ? `<i class=\"bi bi-geo-alt\"></i> ${e.location}` : ''}
                ${e.start_date ? ` · <i class=\"bi bi-clock\"></i> ${whenText}` : ''}
            </div>
            ${e.description ? `<div class=\"mb-2\">${e.description}</div>` : ''}
            <div class="d-flex flex-wrap gap-2 small">
                <span class="badge bg-secondary-subtle text-secondary"><i class="bi bi-people"></i> ${e.participants_count || 0} going</span>
                ${e.is_going ? '<span class="badge bg-success-subtle text-success"><i class="bi bi-check2-circle"></i> You are going</span>' : ''}
                ${e.is_interested ? '<span class="badge bg-warning-subtle text-warning"><i class="bi bi-star"></i> Interested</span>' : ''}
            </div>
        </div>`;
    } else if (postType === 'product' && post.product_details) {
        const p = post.product_details;
        const price = (typeof p.price === 'number' && p.currency) ? `${p.price.toFixed(2)} ${p.currency}` : '';
        const thumb = p.first_media_url ? `<img class=\"img-fluid rounded-3\" src=\"${p.first_media_url}\" alt=\"${p.name}\">` : '';
        specialSectionHtml = `
        <div class="border rounded-3 p-3 mb-3 bg-light">
            <div class="d-flex align-items-center mb-2">
                <span class="badge bg-success me-2"><i class="bi bi-bag"></i> Product</span>
                <h5 class="mb-0">${p.name || ''}</h5>
            </div>
            <div class="row g-3 align-items-start">
                ${thumb ? `<div class=\"col-12 col-md-5\">${thumb}</div>` : ''}
                <div class="${thumb ? 'col-12 col-md-7' : 'col-12'}">
                    ${price ? `<div class=\"fs-5 fw-semibold mb-2 text-success\">${price}</div>` : ''}
                    ${p.description ? `<div class=\"mb-2\">${p.description}</div>` : ''}
                    <div class="small text-muted">
                        ${p.location ? `<span><i class=\"bi bi-geo-alt\"></i> ${p.location}</span>` : ''}
                        ${p.category ? `<span class=\"ms-2\"><i class=\"bi bi-tag\"></i> ${p.category.name}</span>` : ''}
                    </div>
                </div>
            </div>
        </div>`;
    }

    // Build reaction summary with counts
    let totalReactions = 0;
    const reactionCounts = post.stats.reaction_counts || {};
    
    // Sum all reaction counts
    for (const [type, count] of Object.entries(reactionCounts)) {
        totalReactions += count;
    }

    // Create reaction icons summary - only show icons for reactions that have counts > 0
    let reactionIcons = '';
    if (reactionCounts.like > 0) reactionIcons += '<span class="reaction-icon reaction-like"></span>';
    if (reactionCounts.love > 0) reactionIcons += '<span class="reaction-icon reaction-love"></span>';
    if (reactionCounts.haha > 0) reactionIcons += '<span class="reaction-icon reaction-haha"></span>';
    if (reactionCounts.wow > 0) reactionIcons += '<span class="reaction-icon reaction-wow"></span>';
    if (reactionCounts.sad > 0) reactionIcons += '<span class="reaction-icon reaction-sad"></span>';
    if (reactionCounts.angry > 0) reactionIcons += '<span class="reaction-icon reaction-angry"></span>';
    
    // If no reactions, show the default icon
    if (reactionIcons === '') {
        reactionIcons = '<span class="reaction-none"><i class="bi bi-hand-thumbs-up text-muted"></i></span>';
    }
    
    // Get privacy level text
    let privacyText = 'Public';
    let privacyIcon = 'bi-globe';
    
    if (post.settings.privacy_level === 2) {
        privacyText = 'Friends';
        privacyIcon = 'bi-people';
    } else if (post.settings.privacy_level === 3) {
        privacyText = 'Only Me';
        privacyIcon = 'bi-lock';
    }

    // Create sharedPostHtml if it's a shared post
    let sharedPostHtml = '';
    if (post.shared_text !== null && post.parent_post_id > 0) {
        sharedPostHtml = `
        <div class="shared-post-container border rounded-3 p-3 mb-3">
            <div class="d-flex align-items-center mb-2">
                <div class="avatar me-2">
                    <img src="${post.shared_from ? post.shared_from.avatar : avatar}" class="avatar rounded-circle" alt="Shared from">
                </div>
                <div>
                    <h6 class="mb-0 fw-bold"><a href="#" class="text-decoration-none text-reset">
                        ${post.shared_from ? post.shared_from.first_name + ' ' + post.shared_from.last_name : author.first_name + ' ' + author.last_name}
                    </a></h6>
                    <span class="small text-muted">${post.shared_from ? formatTimeAgo(post.shared_from_date) : ''}</span>
                </div>
            </div>
            <p>${post.shared_text || ''}</p>
        </div>`;
    }

    var totalRectionsHtml = '';
    if(totalReactions > 0){
        totalRectionsHtml = `<span class="small reaction-count-summary">${totalReactions > 0 ? totalReactions : 0}</span>`;
    }
    var coloredPostClass = '';
    if(post.background.color != "" && post.background.text_color != null){
        coloredPostClass = 'colored-post';
    }

    let postHtml = `
    <!-- Post Card START -->
    <div class="card post_card shadow-sm border-0 mb-4" id="post-${post.id}" data-original-text="${escapeHtml(postText).replace(/"/g, '&quot;')}">
        <!-- Card Header -->
        <div class="card-header border-0 pb-0 pt-3 d-flex align-items-center justify-content-between bg-transparent">
            <div class="d-flex align-items-center">
                <!-- Avatar -->
                <div class="avatar me-2">
                    <a href="${profileUrl}" class="d-block position-relative">
                        <img class="avatar rounded-circle border" src="${avatar}" alt="User Avatar">
                        <span class="avatar-status bg-success"></span>
                    </a>
                </div>
                <!-- User Info -->
                <div>
                    <div class="nav nav-divider">
                        <h6 class="nav-item mb-0">
                            <a href="${profileUrl}" class="text-body fw-semibold text-decoration-none">${authorName}</a>
                            ${feelingText}
                            ${post.tagged && post.tagged.length ? renderTaggedLine(post.tagged) : ''}
                        </h6>
                        ${contextLine ? `<div class=\"mt-1\">${contextLine}</div>` : ''}
                    </div>
                    <div class="d-flex align-items-center mt-1">
                        <span class="small text-muted">${timeAgo}</span>
                        <span class="small mx-2">•</span>
                        <span class="small text-muted"><i class="bi ${privacyIcon} me-1"></i> ${privacyText}</span>
                    </div>
                </div>
            </div>
            <!-- Post Actions Dropdown -->
            <div class="dropdown">
                <button class="btn btn-sm " data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="bi bi-three-dots"></i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                </button>
                <ul class="dropdown-menu dropdown-menu-end shadow-sm border-0">
                    ${isPostOwner ? `<li><a class="dropdown-item edit-post-btn" href="javascript:void(0)" data-post-id="${post.id}"><i class="bi bi-pencil-square pe-2"></i> Edit Post</a></li>` : ''}
                    <li><a class="dropdown-item save-post-btn" href="javascript:void(0)" data-post-id="${post.id}" data-saved="${post.stats.is_saved ? '1' : '0'}">
                        <i class="bi ${post.stats.is_saved ? 'bi-bookmark-check-fill' : 'bi-bookmark'} pe-2"></i> 
                        ${post.stats.is_saved ? 'Unsave Post' : 'Save Post'}
                    </a></li>
                    ${isPostOwner ? `<li><a class="dropdown-item toggle-comments-btn" href="javascript:void(0)" data-post-id="${post.id}" data-disabled="${!post.settings.comments_enabled ? '1' : '0'}">
                        <i class="bi ${!post.settings.comments_enabled ? 'bi-chat' : 'bi-chat-slash'} pe-2"></i>
                        ${!post.settings.comments_enabled ? 'Enable Comments' : 'Disable Comments'}
                    </a></li>` : ''}
                    <li><a class="dropdown-item hide-post-btn" href="javascript:void(0)" data-post-id="${post.id}">
                        <i class="bi bi-eye-slash pe-2"></i> Hide Post
                    </a></li>
                    ${!isPostOwner && author && author.id ? `<li><a class="dropdown-item follow-user-btn" href="javascript:void(0)" data-user-id="${author.id}">
                        <i class="bi bi-person-plus pe-2"></i> Follow ${author.first_name}
                    </a></li>` : ''}
                    <li><hr class="dropdown-divider"></li>
                    ${isPostOwner ? `<li><a class="dropdown-item delete-post-btn text-danger" href="javascript:void(0)" data-post-id="${post.id}">
                        <i class="bi bi-trash pe-2"></i> Delete Post
                    </a></li>` : ''}
                    <li><a class="dropdown-item report-post-btn text-danger" href="javascript:void(0)" data-post-id="${post.id}">
                        <i class="bi bi-flag pe-2"></i> Report Post
                    </a></li>
                </ul>
            </div>
        </div>

        <!-- Card Body -->
        <div class="card-body">
            <!-- Location Badge -->
            ${locationBadge}
            
            <!-- Special sections -->
            ${specialSectionHtml}
            
            <!-- Post Text Content -->
            ${postType !== 'poll' ? `<div class="mb-3 fs-6 mt-3 ${coloredPostClass} post-text-content" data-post-text-id="${post.id}">${processPost(postText)}</div>` : ''}
            
            <!-- Shared Post Content -->
            ${sharedPostHtml}
            
            <!-- Media Content -->
            ${mediaHtml}
            
            <!-- Poll Content -->
            ${pollHtml}
            
            <!-- Location Map -->
            ${postLocation}
            
            <!-- Reactions and Comments Summary -->
            <div class="d-flex justify-content-between align-items-center py-2 mb-1">
                <!-- Reactions Summary - clickable to show reactions popup -->
                <div class="d-flex align-items-center ${totalReactions > 0 ? 'cursor-pointer' : ''}" 
                     onclick="${totalReactions > 0 ? `showPostActionsDetail(${post.id}, 'like')` : ''}">
                    <div class="reactions-icons-summary">
                        ${reactionIcons}
                        ${totalRectionsHtml}
                    </div>
                </div>
                
                <!-- Comments and Shares Count -->
                <div class="d-flex small text-muted">
                    <!-- Comments count - clickable to show comments section or popup -->
                    <div class="d-flex align-items-center me-3 ${post.stats.comments > 0 ? 'cursor-pointer' : ''}" 
                         onclick="${post.stats.comments > 0 ? `showComments(${post.id})` : ''}">
                        <span>${post.stats.comments}</span>
                        <span class="ms-1">Comments</span>
                    </div>
                    <!-- Shares count - clickable to show shares popup -->
                    <div class="d-flex align-items-center ${post.stats.shares > 0 ? 'cursor-pointer' : ''}" 
                         onclick="${post.stats.shares > 0 ? `showPostActionsDetail(${post.id}, 'share')` : ''}">
                        <span>${post.stats.shares}</span>
                        <span class="ms-1">Shares</span>
                    </div>
                </div>
            </div>

            <!-- Post Actions -->
            <div class="post-actions d-flex justify-content-between border-top border-bottom py-2 mb-3">
                <div class="action-item">
                    <!-- Like Button with Reaction Menu -->
                    <button class="btn btn-sm position-relative like_action" href="javascript:void(0)">
                        <div class="reaction-icon add_reaction_one visible" style="display: none;"></div>
                        <div class="first_action d-inline-flex">
                            <span class="reaction-icon ${reactionIcon}"></span>
                            <span class="${reactionColor} mt-2">${reactionText}</span>
                        </div>
                        <div class="reaction-box">
                            <div class="reaction-icon like add_reaction" data-reactiontype="1">
                                <label>Like</label>
                            </div>
                            <div class="reaction-icon love add_reaction" data-reactiontype="2">
                                <label>Love</label>
                            </div>
                            <div class="reaction-icon haha add_reaction" data-reactiontype="3">
                                <label>Haha</label>
                            </div>
                            <div class="reaction-icon wow add_reaction" data-reactiontype="4">
                                <label>Wow</label>
                            </div>
                            <div class="reaction-icon sad add_reaction" data-reactiontype="5">
                                <label>Sad</label>
                            </div>
                            <div class="reaction-icon angry add_reaction" data-reactiontype="6">
                                <label>Angry</label>
                            </div>
                        </div>
                    </button>
                </div>
                <div class="action-item">
                    <!-- Comment Button -->
                    <button class="btn btn-light btn-sm" onclick="showComments(${post.id})">
                        <i class="bi bi-chat-text me-1"></i> Comment
                    </button>
                </div>
                <div class="action-item">
                    <!-- Share Button -->
                    <div class="dropdown">
                        <button class="btn btn-light btn-sm dropdown-toggle" type="button" id="shareDropdown${post.id}" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bi bi-share me-1"></i> Share
                        </button>
                        <ul class="dropdown-menu shadow-sm border-0" aria-labelledby="shareDropdown${post.id}">
                            <li><a class="dropdown-item share-now-btn" href="javascript:void(0)" data-post-id="${post.id}">
                                <i class="bi bi-share-fill pe-2"></i> Share now
                            </a></li>
                            <li><a class="dropdown-item share-with-text-btn" href="javascript:void(0)" data-post-id="${post.id}">
                                <i class="bi bi-pencil-square pe-2"></i> Share with post
                            </a></li>
                            <li><a class="dropdown-item share-dm-btn" href="javascript:void(0)" data-post-id="${post.id}">
                                <i class="bi bi-envelope pe-2"></i> Send in Message
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item copy-link-btn" href="javascript:void(0)" data-post-id="${post.id}">
                                <i class="bi bi-link-45deg pe-2"></i> Copy link
                            </a></li>
                        </ul>
                    </div>
                </div>
                ${post.tips_enabled ? `
                <div class="action-item">
                    <button class="btn btn-success btn-sm" onclick="openTipModal(${post.id}, ${post.author ? post.author.id : 0})">
                        <i class="bi bi-cash-coin me-1"></i> Tip
                    </button>
                </div>` : ''}
            </div>

            <!-- Comment Input -->
            <div class="d-flex mb-3 comment-input-container" id="comment-input-${post.id}" ${!post.settings.comments_enabled ? 'style="display:none;"' : ''}>
                <div class="avatar me-2">
                    <a href="#!"><img class="avatar rounded-circle" src="${window.user ? window.user.avatar : avatar}" alt="${window.user ? window.user.name : ''}"></a>
                </div>
                <div class="w-100 position-relative">
                    <input type="text" class="form-control pe-5 bg-light border-0 rounded-pill comment-input" 
                           data-post-id="${post.id}" placeholder="Write a comment..." />
                    <div class="position-absolute end-0 top-50 translate-middle-y d-flex mx-2">
                        <button class="btn btn-link text-decoration-none p-2 comment-emoji-btn" type="button">
                            <i class="bi bi-emoji-smile"></i>
                        </button>
                        <button class="btn btn-link text-decoration-none p-2 post-comment-btn" type="button" data-post-id="${post.id}">
                            <i class="bi bi-send-fill"></i>
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- Comments Section -->
            <div class="comments-section" id="comments-section-${post.id}" style="display:none;"></div>
        </div>
    </div>
    <!-- Post Card END -->
`;

    return postHtml;
}

function renderTaggedLine(tagged) {
    try {
        const firstTwo = tagged.slice(0, 2);
        const extra = tagged.length - firstTwo.length;
        const names = firstTwo.map(u => `${escapeHtml(u.first_name || u.name || '')} ${escapeHtml(u.last_name || '')}`.trim()).join(', ');
        const more = extra > 0 ? ` and ${extra} more` : '';
        return names ? ` <span class="text-muted mx-1">with ${names}${more}</span>` : '';
    } catch (e) {
        return '';
    }
}

// Function to show post actions detail popup (reactions, shares, etc.)
function showPostActionsDetail(postId, actionType) {
    // Create the modal HTML
    const modalTitle = actionType === 'like' ? 'People who reacted to this' : 
                      actionType === 'share' ? 'People who shared this' : 
                      actionType === 'save' ? 'Post saved by' : 'Post reports';
    
    const modalIcon = actionType === 'like' ? 'bi-hand-thumbs-up-fill text-primary' : 
                     actionType === 'share' ? 'bi-share text-info' : 
                     actionType === 'save' ? 'bi-bookmark-fill text-warning' : 'bi-flag-fill text-danger';
    
    const modalId = `postActionsModal-${actionType}-${postId}`;
    
    const modalHtml = `
    <div class="modal fade" id="${modalId}" tabindex="-1" aria-labelledby="${modalId}Label" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title" id="${modalId}Label">
                        <i class="bi ${modalIcon} me-2"></i> ${modalTitle}
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-0">
                    <!-- Tab navigation for reaction types (only for likes) -->
                    ${actionType === 'like' ? `
                    <ul class="nav nav-tabs nav-justified" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#all-reactions-tab-${postId}" type="button" role="tab">
                                All
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#like-reactions-tab-${postId}" type="button" role="tab">
                                <i class="bi bi-hand-thumbs-up-fill text-primary"></i> Like
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#love-reactions-tab-${postId}" type="button" role="tab">
                                <i class="bi bi-heart-fill text-danger"></i> Love
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#other-reactions-tab-${postId}" type="button" role="tab">
                                Other
                            </button>
                        </li>
                    </ul>
                    <div class="tab-content">
                        <div class="tab-pane fade show active" id="all-reactions-tab-${postId}" role="tabpanel">
                            <div class="action-list all-reactions-list p-2" data-reaction-type="all"></div>
                        </div>
                        <div class="tab-pane fade" id="like-reactions-tab-${postId}" role="tabpanel">
                            <div class="action-list like-reactions-list p-2" data-reaction-type="like"></div>
                        </div>
                        <div class="tab-pane fade" id="love-reactions-tab-${postId}" role="tabpanel">
                            <div class="action-list love-reactions-list p-2" data-reaction-type="love"></div>
                        </div>
                        <div class="tab-pane fade" id="other-reactions-tab-${postId}" role="tabpanel">
                            <div class="action-list other-reactions-list p-2" data-reaction-type="other"></div>
                        </div>
                    </div>
                    ` : `
                    <div class="action-list p-2"></div>
                    `}
                    
                    <!-- Loading indicator -->
                    <div class="text-center py-5 loading-indicator">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2 text-muted">Loading...</p>
                    </div>
                    
                    <!-- No results message -->
                    <div class="text-center py-5 no-results-message" style="display: none;">
                        <i class="bi bi-info-circle fs-1 text-muted"></i>
                        <p class="mt-2 text-muted">No ${actionType === 'like' ? 'reactions' : actionType + 's'} found.</p>
                    </div>
                </div>
                
                <!-- Load more button -->
                <div class="modal-footer border-top-0 load-more-container" style="display: none;">
                    <button type="button" class="btn btn-light w-100 load-more-btn">
                        <i class="bi bi-arrow-down-circle me-2"></i> Load More
                    </button>
                </div>
            </div>
        </div>
    </div>`;
    
    // Remove any existing modal
    $(`#${modalId}`).remove();
    
    // Add the modal to the DOM
    $('body').append(modalHtml);
    
    // Initialize and show the modal
    const modal = new bootstrap.Modal(document.getElementById(modalId));
    modal.show();
    
    // Load the initial data
    loadPostActionsData(postId, actionType, 0, 10);
    
    // Add event listener to load more button
    $(`#${modalId} .load-more-btn`).on('click', function() {
        const offset = $(this).data('offset') || 10;
        loadPostActionsData(postId, actionType, offset, 10, true);
    });
    
    // Add event listeners to tab buttons for reaction filtering (only for likes)
    if (actionType === 'like') {
        $(`#${modalId} .nav-link`).on('click', function() {
            const reactionType = $(this).closest('li').find('.tab-pane').find('.action-list').data('reaction-type');
            const $container = $(`#${$(this).data('bs-target')}`).find('.action-list');
            
            // Only load if container is empty
            if ($container.children().length === 0) {
                $container.html('');
                $(`#${modalId} .loading-indicator`).show();
                $(`#${modalId} .no-results-message`).hide();
                
                loadPostActionsData(postId, actionType, 0, 10, false, reactionType);
            }
        });
    }
}

// Function to load post actions data from API
function loadPostActionsData(postId, actionType, offset, limit, append = false, reactionType = 'all') {
    const modalId = `postActionsModal-${actionType}-${postId}`;
    let $container;
    
    if (actionType === 'like' && reactionType !== 'all') {
        // If filtering by reaction type
        $container = $(`#${modalId} .action-list[data-reaction-type="${reactionType}"]`);
    } else {
        // Default container
        $container = $(`#${modalId} .action-list:first`);
    }
    
    // Show loading indicator if not appending
    if (!append) {
        $(`#${modalId} .loading-indicator`).show();
        $(`#${modalId} .no-results-message`).hide();
        if (!$container.data('loading')) {
            $container.html('');
        }
    }
    
    $container.data('loading', true);
    
    // Make API request
    axios.post(base_url + "/webapi/post/post-actions-detail", {
        post_id: postId,
        action_type: actionType,
        offset: offset,
        limit: limit,
        reaction_type: reactionType !== 'all' ? reactionType : null
    })
    .then(response => {
        // Hide loading indicator
        $(`#${modalId} .loading-indicator`).hide();
        $container.data('loading', false);
        
        if (response.data.status === 200) {
            const data = response.data.data || [];
            
            if (data.length === 0) {
                // No results
                if (!append) {
                    $(`#${modalId} .no-results-message`).show();
                }
                $(`#${modalId} .load-more-container`).hide();
                return;
            }
            
            // Hide no results message if there's data
            $(`#${modalId} .no-results-message`).hide();
            
            // Clear container if not appending
            if (!append) {
                $container.html('');
            }
            
            // Render each action item
            data.forEach(item => {
                let reactionIcon = '';
                let reactionClass = '';
                
                if (actionType === 'like') {
                    // Determine reaction icon and class based on reaction type
                    if (item.reaction_type === 'like' || item.reaction_type === 1) {
                        reactionIcon = '<i class="bi bi-hand-thumbs-up-fill text-primary"></i>';
                        reactionClass = 'reaction-like';
                    } else if (item.reaction_type === 'love' || item.reaction_type === 2) {
                        reactionIcon = '<i class="bi bi-heart-fill text-danger"></i>';
                        reactionClass = 'reaction-love';
                    } else if (item.reaction_type === 'haha' || item.reaction_type === 3) {
                        reactionIcon = '<i class="bi bi-emoji-laughing-fill text-warning"></i>';
                        reactionClass = 'reaction-haha';
                    } else if (item.reaction_type === 'wow' || item.reaction_type === 4) {
                        reactionIcon = '<i class="bi bi-emoji-surprise-fill text-info"></i>';
                        reactionClass = 'reaction-wow';
                    } else if (item.reaction_type === 'sad' || item.reaction_type === 5) {
                        reactionIcon = '<i class="bi bi-emoji-frown-fill text-secondary"></i>';
                        reactionClass = 'reaction-sad';
                    } else if (item.reaction_type === 'angry' || item.reaction_type === 6) {
                        reactionIcon = '<i class="bi bi-emoji-angry-fill text-danger"></i>';
                        reactionClass = 'reaction-angry';
                    }
                } else if (actionType === 'share') {
                    reactionIcon = '<i class="bi bi-share text-info"></i>';
                } else if (actionType === 'save') {
                    reactionIcon = '<i class="bi bi-bookmark-fill text-warning"></i>';
                }
                
                // Create HTML for each action item
                const itemHtml = `
                <div class="action-item d-flex align-items-center p-2 border-bottom">
                    <div class="avatar me-3">
                        <a href="#!">
                            <img class="avatar rounded-circle" src="${item.user.avatar}" alt="${item.user.first_name} ${item.user.last_name}">
                        </a>
                    </div>
                    <div class="flex-grow-1">
                        <h6 class="mb-0">
                            <a href="#!" class="text-reset text-decoration-none fw-semibold">${item.user.first_name} ${item.user.last_name}</a>
                        </h6>
                        <small class="text-muted">${item.date ? formatTimeAgo(item.date) : ''}</small>
                    </div>
                    <div class="reaction-badge ${reactionClass}">
                        ${reactionIcon}
                    </div>
                </div>`;
                
                $container.append(itemHtml);
            });
            
            // Update load more button
            if (data.length === limit) {
                const newOffset = offset + limit;
                $(`#${modalId} .load-more-btn`).data('offset', newOffset);
                $(`#${modalId} .load-more-container`).show();
            } else {
                $(`#${modalId} .load-more-container`).hide();
            }
        } else {
            // Error handling
            $(`#${modalId} .no-results-message`).find('p').text('Error loading data. Please try again.');
            $(`#${modalId} .no-results-message`).show();
            $(`#${modalId} .load-more-container`).hide();
        }
    })
    .catch(error => {
        console.error("Error:", error);
        $(`#${modalId} .loading-indicator`).hide();
        $(`#${modalId} .no-results-message`).find('p').text('Error loading data. Please try again.');
        $(`#${modalId} .no-results-message`).show();
        $(`#${modalId} .load-more-container`).hide();
        $container.data('loading', false);
    });
}

function showLoadingAnimation() {
    return `
    <div class="card post_card shadow-sm border-0 mb-4 loading_animation" style="border-radius: 10px;">
        <div class="card-header border-0 pb-0 pt-3 d-flex align-items-center justify-content-between bg-transparent">
            <div class="d-flex align-items-center">
                <div class="skeleton-avatar rounded-circle me-3"></div>
                <div>
                    <div class="skeleton-text w-100" style="max-width: 140px;"></div>
                    <div class="skeleton-text w-75 mt-1" style="max-width: 90px; height: 10px;"></div>
                </div>
            </div>
            <div class="skeleton-text rounded-circle" style="width: 28px; height: 28px;"></div>
        </div>
        <div class="card-body">
            <div class="skeleton-text w-100 mb-2"></div>
            <div class="skeleton-text w-75 mb-3"></div>
            <div class="skeleton-image w-100 mb-3" style="border-radius: 10px;"></div>
            <div class="d-flex justify-content-between align-items-center py-2 mb-1">
                <div class="d-flex align-items-center">
                    <div class="d-flex skeleton-text rounded-circle" style="width: 20px; height: 20px;"></div>
                    <div class="skeleton-text ms-2" style="width: 40px; height: 12px;"></div>
                </div>
                <div class="d-flex">
                    <div class="skeleton-text me-3" style="width: 60px; height: 12px;"></div>
                    <div class="skeleton-text" style="width: 50px; height: 12px;"></div>
                </div>
            </div>
            <div class="d-flex justify-content-between pt-2 pb-1 mt-1" style="border-top: 1px solid #eee;">
                <div class="skeleton-text" style="height: 30px; width: 30%;"></div>
                <div class="skeleton-text" style="height: 30px; width: 30%;"></div>
                <div class="skeleton-text" style="height: 30px; width: 30%;"></div>
            </div>
        </div>
    </div>`;
}
var is_plyr_loaded = 0;
function loadNewsFeed(postId = null) {
    if (isLoading) return; // Prevent multiple requests at the same time

    isLoading = true;
    
    // Show loading skeletons if not loading a specific post
    if (!postId) {
        $("#postholder").append(showLoadingAnimation() + showLoadingAnimation());
    }

    // Prepare request payload
    let requestData = {
        offset: offset, // Use offset for pagination
        limit: limit
    };

    // If postId is provided, include it in the request data
    if (postId) {
        requestData.post_id = postId;
    }
    // Get post type from hidden input
    let postType = $("#postType").val() || 'all';
    if (postType === 'group_post') {
        // Get group id from hidden input, if it exists
        let groupId = $("#groupId").val();
        if (groupId) {
            requestData.group_id = groupId;
        }
    }
    if (postType === 'page_post') {  
        // Get page id from hidden input, if it exists
        let pageId = $("#pageId").val();
        if (pageId) {
            requestData.page_id = pageId;
        }
    }

    if (postType !== 'all') {
        requestData.post_type = postType;
    } else {
        requestData.post_type = null;
    }

    const profileUserId = getProfileUserId();
    if (profileUserId) {
        requestData.user_id = profileUserId;
    }

    axios.post(base_url + "/webapi/post/newsfeed", requestData)
        .then(response => {
            // Remove loading skeletons first
            $(".loading_animation").remove();
            
            if (response.data.status !== 200) {
                console.error("Error fetching posts:", response.data.message);
                showAlert('error', 'Error', 'Failed to load newsfeed!');
                return;
            }

            let posts = response.data.data;
            let fragment = $(document.createDocumentFragment());
            var postIds = [];
            if (posts.length > 0) {
                posts.forEach(post => {
                    fragment.append(renderPost(post));
                    postIds.push(`#post-${post.id}`);
                });

                if (postId) {
                    // If fetching a single post, replace existing content instead of appending
                    $("#postholder").prepend(fragment);
                } else {
                    // Append new posts for normal newsfeed loading
                    $("#postholder").append(fragment);
                    offset += limit; // Increase offset for next request
                }
                postIds.forEach(ids=> {
                    initPlayers(document.querySelector(ids));
                })
            } else if (!postId) {
                // Show end of feed message
                $("#postholder").append(`
                    <div class="text-center py-4 text-muted">
                        <i class="bi bi-check-circle-fill fs-1"></i>
                        <p class="mt-2">You've reached the end of your feed!</p>
                    </div>
                `);
                // Stop infinite scroll only if loading paginated feed
                $(window).off("scroll", handleScroll);
            }
        })
        .catch(error => {
            // Remove loading skeletons
            $(".loading_animation").remove();
            
            console.error("Error:", error);
            // showAlert('error', 'Error', 'Failed to load data!');
        })
        .finally(() => {
            isLoading = false;
        });
}

// Function to check if the user scrolled to 75% of the page
function handleScroll() {
    const profileUserId = getProfileUserId();
    if (profileUserId) {
        const timelinePane = document.getElementById('timeline');
        if (timelinePane && !timelinePane.classList.contains('show')) {
            return;
        }
    }
    let scrollTop = $(window).scrollTop();
    let documentHeight = $(document).height();
    let windowHeight = $(window).height();
    let scrollPercentage = (scrollTop + windowHeight) / documentHeight;

    if (scrollPercentage >= 0.75) {
        loadNewsFeed();
    }
}


// Function to edit a comment
function editComment(commentId, postId) {
    // Get current comment text
    const commentElement = $(`#comment-${commentId} .comment-text, #reply-${commentId} .reply-text`);
    const currentText = commentElement.text();
    
    // Replace with editable textarea
    commentElement.html(`
        <div class="edit-comment-form">
            <textarea class="form-control mb-2" rows="2">${currentText}</textarea>
            <div class="d-flex justify-content-end">
                <button class="btn btn-sm btn-outline-secondary me-2" onclick="cancelEditComment(${commentId}, '${currentText.replace(/'/g, "\\'")}')">
                    Cancel
                </button>
                <button class="btn btn-sm btn-primary" onclick="saveEditComment(${commentId}, ${postId})">
                    Save
                </button>
            </div>
        </div>
    `);
    
    // Focus the textarea and put cursor at the end
    const textarea = commentElement.find('textarea');
    textarea.focus();
    textarea.val('').val(currentText);
}

// Function to cancel comment editing
function cancelEditComment(commentId, originalText) {
    const commentElement = $(`#comment-${commentId} .comment-text, #reply-${commentId} .reply-text`);
    commentElement.html(originalText);
}

// Function to save edited comment
function saveEditComment(commentId, postId) {
    const commentElement = $(`#comment-${commentId} .comment-text, #reply-${commentId} .reply-text`);
    const newText = commentElement.find('textarea').val();
    
    // Call API to update the comment
    axios.post(base_url + "/webapi/post/comment-action", {
        comment_id: commentId,
        post_id: postId,
        action: 'edit',
        content: newText
    })
    .then(response => {
        if (response.data.status === 200) {
            // Update the UI with the edited text
            commentElement.html(newText);
            
            // Add edited label if not already there
            const timeContainer = commentElement.closest('.comment-bubble, .reply-bubble')
                                    .find('.d-flex.justify-content-between.align-items-center div:first-child');
            
            if (!timeContainer.find('.text-muted.fs-xs').length) {
                timeContainer.append('<span class="text-muted fs-xs ms-2">(Edited)</span>');
            }
            
            // Show success message
            showAlert('success', 'Success', 'Comment updated successfully');
        } else {
            showAlert('error', 'Error', response.data.message);
            // Revert to original text
            cancelEditComment(commentId, newText);
        }
    })
    .catch(error => {
        console.error("Error:", error);
        showAlert('error', 'Error', 'Failed to update comment');
        // Revert to original text
        cancelEditComment(commentId, newText);
    });
}

function showMap(latLng){
    const [lat, lng] = latLng.split(', ').map(coord => parseFloat(coord));
    const mapHtml = `<div class="map-container"><iframe 
                width="100%" 
                height="300" 
                src="https://www.google.com/maps/embed/v1/view?key=AIzaSyAOVYRIgupAurZup5y1PRh8Ismb1A3lLao&center=${lat},${lng}&zoom=14" 
                frameborder="0" 
                style="border:0" 
                allowfullscreen>
    </iframe></div>`;
    return mapHtml;
}



function reactToPost(postId, reactionType) {
    axios.post(base_url + "/webapi/post/action", {
        post_id: postId,
        action: 'reaction',
        reaction_type: reactionType
    })
    .then(response => {
        if (response.status === 200) {
            updatePostReaction(postId, reactionType, response.data.is_reacted, response.data.total_reactions, response.data.reaction_counts);
        } else {
            showAlert('error', 'Error', response.data.message);
        }
    })
    .catch(error => {
        console.error("Error:", error);
        showAlert('error', 'Error', 'Failed to react to post.');
    });
}

// Poll voting
function voteOnPoll(postId, optionId) {
    axios.post(base_url + "/webapi/post/action", {
        post_id: postId,
        action: 'poll_vote',
        option_id: optionId
    }).then(response => {
        if (response.data && response.data.status === 200 && response.data.data) {
            updatePollUI(postId, response.data.data);
        } else {
            showAlert('error', 'Poll', 'Failed to submit vote.');
        }
    }).catch(() => {
        showAlert('error', 'Poll', 'Failed to submit vote.');
    });
}

function updatePollUI(postId, pollData) {
    const $card = $("#post-" + postId);
    const $container = $card.find('.poll-container');
    if ($container.length === 0) return;
    // Update total votes
    $container.find('.poll-total-votes').text(pollData.total_votes || 0);
    // Update each option
    if (Array.isArray(pollData.options)) {
        pollData.options.forEach(opt => {
            const inputId = `#poll-${postId}-option-${opt.id}`;
            const $input = $container.find(inputId);
            if ($input.length) {
                // Mark selected
                $input.prop('checked', pollData.my_option_id === opt.id);
                // Find progress and percentage label within the same label
                const $label = $container.find(`label[for="poll-${postId}-option-${opt.id}"]`);
                const $bar = $label.find('.progress-bar');
                const $percent = $label.find('.small');
                $bar.css('width', (opt.percentage || 0) + '%').attr('aria-valuenow', opt.percentage || 0);
                $percent.text((opt.percentage || 0) + '%');
            }
        });
    }
}

// Bind change event for poll radio buttons
$(document).on('change', '.poll-container input.poll-radio', function () {
    const $this = $(this);
    const postIdMatch = $this.attr('name').match(/^poll-(\d+)$/);
    if (!postIdMatch) return;
    const postId = parseInt(postIdMatch[1]);
    const optionId = parseInt($this.val());
    if (!isNaN(postId) && !isNaN(optionId)) {
        voteOnPoll(postId, optionId);
    }
});

function updatePostReaction(postId, reactionType, isReacted, total, allCounts) {
    const reactionCountElement = $(`#post-${postId} .reaction-count-summary`);
    let currentReactions = parseInt(reactionCountElement.text()) || 0;
    const userReaction = reactionType;
    const reactionAllEl = $(`#post-${postId} .reactions-icons-summary`);
    // Update reaction UI based on reaction type
    let reactionText = 'Like';
    let reactionColor = '';
    let reactionIcon = 'reaction-like';
    
    if (isReacted) {
        // Increase reaction count if new reaction
        const newCount = total;
        reactionCountElement.text(newCount > 0 ? newCount : '');
        //1,2,3,4,5', // Example: 1=Like, 2=Love, 3=Haha, 4=Wow, 5=Sad
        if (userReaction === 1) {
            reactionText = 'Like';
            reactionColor = 'text-primary';
            reactionIcon = 'reaction-like';
        } else if (userReaction === 2) {
            reactionText = 'Love';
            reactionColor = 'text-danger';
            reactionIcon = 'reaction-love';
        } else if (userReaction === 3) {
            reactionText = 'Haha';
            reactionColor = 'text-warning';
            reactionIcon = 'reaction-laugh';
        } else if (userReaction === 4) {
            reactionText = 'Wow';
            reactionColor = 'text-info';
            reactionIcon = 'reaction-wow';
        } else if (userReaction === 5) {
            reactionText = 'Sad';
            reactionColor = 'text-secondary';
            reactionIcon = 'reaction-sad';
        } else if (userReaction === 6) {
            reactionText = 'Angry';
            reactionColor = 'text-warning';
            reactionIcon = 'reaction-angry';
        }
    } else {
        // Decrease reaction count if reaction removed
        const newCount = Math.max(0, currentReactions - 1);
        reactionCountElement.text(newCount > 0 ? newCount : '');
        
        // Reset to default if reaction removed
        reactionText = 'React';
        reactionColor = '';
        reactionIcon = 'reaction-like';
    }
    let allRecs = "";
    const reactionClasses = {
        like: "reaction-like",
        love: "reaction-love",
        haha: "reaction-haha",
        wow: "reaction-wow",
        sad: "reaction-sad",
        angry: "reaction-angry"
    };

    $.each(allCounts, function (reaction, count) {
        if (count > 0) {
            allRecs += `<span class="reaction-icon ${reactionClasses[reaction]}"></span>`;
        }
    });
    
    // Update reaction button appearance
    const likeBtn = $(`#post-${postId} .first_action`);
    likeBtn.html(`<span class="reaction-icon ${reactionIcon}"></span>
                            <span class="${reactionColor} mt-2">${reactionText}</span>`);
    likeBtn.removeClass('text-primary text-danger text-warning text-info text-secondary');
    reactionAllEl.html('').html(allRecs+`<span class="small reaction-count-summary">${total}</span>`);
    
    if (isReacted) {
        likeBtn.addClass(reactionColor);
    }
    
    // Update reaction icons in the summary
    updateReactionIconsSummary(postId, reactionType, isReacted);
}

// Function to update the reaction icons summary
function updateReactionIconsSummary(postId, reactionType, isReacted) {
    // This would typically update the reaction icons shown in the post summary
    // For a complete implementation, you would need to fetch the updated counts from the server
    // and rebuild the reaction icons summary
    
    // For now, we'll just toggle the visibility of the reaction icon
    const reactionIconsContainer = $(`#post-${postId} .reactions-icons-summary`);
    
    // In a real implementation, you would update this based on the server response
    // with the actual counts for each reaction type
}

function savePost(postId) {
    const saveBtn = $(`.save-post-btn[data-post-id="${postId}"]`);
    const isSaved = saveBtn.data('saved') === 1;
    
    axios.post(base_url + "/webapi/post/action", {
        post_id: postId,
        action: 'save'
    })
    .then(response => {
        if (response.data.status === 200) {
            // Toggle saved state UI
            if (isSaved) {
                // Post was saved, now unsaved
                saveBtn.html('<i class="bi bi-bookmark pe-2"></i> Save Post');
                saveBtn.data('saved', 0);
                showAlert('success', 'Success', 'Post unsaved successfully');
        } else {
                // Post was not saved, now saved
                saveBtn.html('<i class="bi bi-bookmark-check-fill pe-2"></i> Unsave Post');
                saveBtn.data('saved', 1);
                showAlert('success', 'Success', 'Post saved successfully');
            }
        } else {
            showAlert('error', 'Error', response.data.message);
        }
    })
    .catch(error => {
        console.error("Error:", error);
        showAlert('error', 'Error', 'Failed to save/unsave post.');
    });
}

function deletePost(postId) {
    // Confirm before deletion
    if (!confirm('Are you sure you want to delete this post? This action cannot be undone.')) {
        return;
    }
    
    axios.post(base_url + "/webapi/post/action", {
        post_id: postId,
        action: 'delete'
    })
    .then(response => {
        if (response.status === 200) {
            // Remove post from UI with animation
            $(`#post-${postId}`).fadeOut(300, function() {
                $(this).remove();
            });
            showAlert('success', 'Success', 'Post deleted successfully');
        } else {
            showAlert('error', 'Error', response.message);
        }
    })
    .catch(error => {
        showAlert('error', 'Error', error.response?.data?.message || 'Failed to perform this action.');
    });
}

// Function to open edit post modal
function openEditPostModal(postId) {
    // Create modal ID
    const modalId = `editPostModal-${postId}`;
    
    // Remove existing modal if any
    $(`#${modalId}`).remove();
    
    // Create modal HTML with loading state
    const modalHtml = `
        <div class="modal fade" id="${modalId}" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Edit Post</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Post Text</label>
                            <div class="text-center py-3">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-2 text-muted">Loading post content...</p>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" id="save-edit-post-btn-${postId}" onclick="saveEditedPost(${postId})" disabled>Save Changes</button>
                    </div>
                </div>
            </div>
        </div>`;
    
    // Append modal to body
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById(modalId));
    modal.show();
    
    // Fetch post detail to get original text
    axios.get(base_url + `/webapi/post/detail/${postId}`)
        .then(response => {
            if (response.status === 200 && response.data.status === 200) {
                const post = response.data.data;
                const currentText = post.text || '';
                
                // Update modal body with textarea
                const modalBody = $(`#${modalId} .modal-body`);
                modalBody.html(`
                    <div class="mb-3">
                        <label class="form-label">Post Text</label>
                        <textarea class="form-control" id="edit-post-text-${postId}" rows="6" placeholder="What's on your mind?">${escapeHtml(currentText)}</textarea>
                        <div class="form-text">You can edit only the text content of your post.</div>
                    </div>
                `);
                
                // Enable save button
                $(`#save-edit-post-btn-${postId}`).prop('disabled', false);
                
                // Focus textarea
                $(`#edit-post-text-${postId}`).focus();
            } else {
                showAlert('error', 'Error', 'Failed to load post content');
                modal.hide();
            }
        })
        .catch(error => {
            showAlert('error', 'Error', error.response?.data?.message || 'Failed to load post content. Please try again.');
            modal.hide();
        });
    
    // Clean up modal when hidden
    $(`#${modalId}`).on('hidden.bs.modal', function() {
        $(this).remove();
    });
}

// Function to save edited post
function saveEditedPost(postId) {
    const textarea = $(`#edit-post-text-${postId}`);
    const newText = textarea.val().trim();
    
    // Validate text
    if (!newText) {
        showAlert('warning', 'Validation Error', 'Post text cannot be empty');
        return;
    }
    
    if (newText.length > 5000) {
        showAlert('warning', 'Validation Error', 'Post text cannot exceed 5000 characters');
        return;
    }
    
    // Disable save button during request
    const saveButton = $(`#editPostModal-${postId} .btn-primary`);
    const originalButtonText = saveButton.html();
    saveButton.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Saving...');
    
    // Send AJAX request to update post
    axios.post(base_url + `/webapi/post/update/${postId}`, {
        post_text: newText
    })
    .then(response => {
        // Check if response is successful (HTTP 200 and status 200 in response data)
        const httpStatus = response.status;
        const responseData = response.data || {};
        const responseStatus = responseData.status;
        
        // Log for debugging
        console.log('Update post response:', {
            httpStatus: httpStatus,
            responseStatus: responseStatus,
            message: responseData.message,
            data: responseData.data
        });
        
        // Check if response is successful - HTTP 200 and status 200 in response
        if (httpStatus === 200 && responseStatus === 200) {
            try {
                // Update the post text in the DOM
                const postElement = $(`#post-${postId}`);
                if (!postElement.length) {
                    console.error('Post element not found in DOM');
                    throw new Error('Post element not found');
                }
                
                // Find post text element - first try by data attribute (most reliable)
                let postTextElement = postElement.find(`.post-text-content[data-post-text-id="${postId}"]`);
                
                // If not found by data attribute, try by classes
                if (!postTextElement.length) {
                    postTextElement = postElement.find('.card-body > .mb-3.fs-6.mt-3.post-text-content').first();
                }
                
                // If still not found, try without the post-text-content class (for older posts)
                if (!postTextElement.length) {
                    postTextElement = postElement.find('.card-body > .mb-3.fs-6.mt-3').first();
                }
                
                // If still not found, try without the direct child selector
                if (!postTextElement.length) {
                    postTextElement = postElement.find('.card-body .mb-3.fs-6.mt-3').first();
                }
                
                // If still not found, try finding by looking for the div that contains the post text
                // (it should be after location badge and special sections, before shared post)
                if (!postTextElement.length) {
                    const cardBody = postElement.find('.card-body');
                    // Find all divs with mb-3 class and check which one contains the post text
                    cardBody.children('div').each(function() {
                        const $div = $(this);
                        // Check if this div has the classes we're looking for
                        if ($div.hasClass('mb-3') && $div.hasClass('fs-6') && $div.hasClass('mt-3')) {
                            // Check if it's not a poll container or other special element
                            if (!$div.hasClass('poll-container') && !$div.closest('.shared-post-container').length) {
                                postTextElement = $div;
                                return false; // break the loop
                            }
                        }
                    });
                }
                
                if (postTextElement.length) {
                    // Update the text content, preserving any HTML structure if needed
                    // Use processPost to handle hashtags and links
                    postTextElement.html(processPost(newText));
                    console.log('Post text updated successfully in DOM');
                } else {
                    console.warn('Post text element not found in DOM. Attempting alternative update method...');
                    
                    // Alternative: Use the response data to update the post
                    // The API returns the updated post data, so we can use it
                    if (responseData.data && responseData.data.text) {
                        // Try to find any element that might contain the post text
                        // Look for elements that might contain text content
                        const cardBody = postElement.find('.card-body');
                        
                        // Try to find the post text by looking for elements that don't have specific classes
                        // that indicate they're not the post text (like poll-container, shared-post-container, etc.)
                        let found = false;
                        cardBody.children().each(function() {
                            const $elem = $(this);
                            // Skip known non-text elements
                            if ($elem.hasClass('poll-container') || 
                                $elem.hasClass('shared-post-container') ||
                                $elem.hasClass('mb-3') && $elem.find('video, audio, img').length > 0) {
                                return true; // continue
                            }
                            
                            // If this element has mb-3 and fs-6 classes, it might be the post text
                            if ($elem.hasClass('mb-3') && $elem.hasClass('fs-6')) {
                                $elem.html(processPost(newText));
                                found = true;
                                console.log('Post text updated using alternative method');
                                return false; // break
                            }
                        });
                        
                        if (!found) {
                            // Last resort: try to insert or update the post text
                            // Find the card body and look for the first text-containing div
                            const firstTextDiv = cardBody.children('div').not('.poll-container, .shared-post-container').first();
                            if (firstTextDiv.length && !firstTextDiv.find('video, audio, img, .gallery').length) {
                                firstTextDiv.html(processPost(newText));
                                console.log('Post text updated using last resort method');
                            } else {
                                console.error('Could not find post text element. Post updated on server but DOM not updated.');
                            }
                        }
                    }
                }
                
                // Update data attribute for future edits
                postElement.attr('data-original-text', escapeHtml(newText).replace(/"/g, '&quot;'));
                
                // Close modal
                const modalElement = document.getElementById(`editPostModal-${postId}`);
                if (modalElement) {
                    const modal = bootstrap.Modal.getInstance(modalElement);
                    if (modal) {
                        modal.hide();
                    }
                }
                
                // Show success message from API or default
                const successMessage = responseData.message || 'Post updated successfully';
                showAlert('success', 'Success', successMessage);
            } catch (domError) {
                console.error('Error updating DOM after post update:', domError);
                // Even if DOM update fails, show success since API call was successful
                const modalElement = document.getElementById(`editPostModal-${postId}`);
                if (modalElement) {
                    const modal = bootstrap.Modal.getInstance(modalElement);
                    if (modal) {
                        modal.hide();
                    }
                }
                showAlert('success', 'Success', responseData.message || 'Post updated successfully. Please refresh to see changes.');
            }
        } else {
            // Handle non-200 status in response data
            const errorMessage = responseData.message || 'Failed to update post';
            console.error('Update post failed:', {
                httpStatus: httpStatus,
                responseStatus: responseStatus,
                message: errorMessage
            });
            showAlert('error', 'Error', errorMessage);
            saveButton.prop('disabled', false).html(originalButtonText);
        }
    })
    .catch(error => {
        console.error('Error updating post:', error);
        
        // Handle different error types
        let errorMessage = 'Failed to update post. Please try again.';
        
        if (error.response) {
            // Server responded with error status
            const status = error.response.status;
            const data = error.response.data;
            
            if (data && data.message) {
                errorMessage = data.message;
            } else if (status === 403) {
                errorMessage = 'You do not have permission to edit this post.';
            } else if (status === 404) {
                errorMessage = 'Post not found.';
            } else if (status === 422) {
                errorMessage = 'Validation error. Please check your input.';
            } else if (status >= 500) {
                errorMessage = 'Server error. Please try again later.';
            }
        } else if (error.request) {
            // Request was made but no response received
            errorMessage = 'Network error. Please check your connection and try again.';
        }
        
        showAlert('error', 'Error', errorMessage);
        saveButton.prop('disabled', false).html(originalButtonText);
    });
}

function removeSelectedFeeling() {
    $('.selected-feeling-badge').remove();
    $('#feeling-category').val('');
    $('#feeling-description').val('');
    
    // Hide posting detail if no other sections are open
    if (!$('#pollSection').is(':visible') && !$('#locationSection').is(':visible')) {
        $('.posting-detail').slideUp(300);
    }
}

function resetFeelingSelection() {
    $('#feeling-category').val('');
    $('#feeling-description').val('');
    $('.selected-feeling-badge').remove();
    $('#feelingSubOptions').hide();
    $('#feelingOptionsGrid').empty();
    $('.feeling-category').removeClass('active');
}

function toggleComments(postId) {
    const toggleBtn = $(`.toggle-comments-btn[data-post-id="${postId}"]`);
    const isDisabled = toggleBtn.data('disabled') === 1;
    
    axios.post(base_url + "/webapi/post/action", {
        post_id: postId,
        action: isDisabled ? 'enablecomments' : 'disablecomments'
    })
    .then(response => {
        if (response.data.status === 200) {
            // Toggle comments UI
            if (isDisabled) {
                // Comments were disabled, now enabled
                toggleBtn.html('<i class="bi bi-chat-slash pe-2"></i> Disable Comments');
                toggleBtn.data('disabled', 0);
                $(`#comment-input-${postId}`).slideDown();
                showAlert('success', 'Success', 'Comments enabled successfully');
            } else {
                // Comments were enabled, now disabled
                toggleBtn.html('<i class="bi bi-chat pe-2"></i> Enable Comments');
                toggleBtn.data('disabled', 1);
                $(`#comment-input-${postId}`).slideUp();
                showAlert('success', 'Success', 'Comments disabled successfully');
            }
        } else {
            showAlert('error', 'Error', response.data.message);
        }
    })
    .catch(error => {
        showAlert('error', 'Error', error.response?.data?.message || 'Failed to perform this action.');
    });
}

function reportPost(postId) {
    // Show a modal or a form to select report reason
    const reportReasons = [
        'Spam or misleading',
        'Abusive or harmful',
        'Inappropriate content',
        'Violates terms of service',
        'Other'
    ];
    
    let reasonOptions = '';
    reportReasons.forEach((reason, index) => {
        reasonOptions += `<div class="form-check mb-2">
            <input class="form-check-input" type="radio" name="reportReason" id="reason${index}" value="${reason}" ${index === 0 ? 'checked' : ''}>
            <label class="form-check-label" for="reason${index}">${reason}</label>
        </div>`;
    });
    
    const reportModalHtml = `
    <div class="modal fade" id="reportModal" tabindex="-1" aria-labelledby="reportModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="reportModalLabel">Report Post</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Please select a reason for reporting this post:</p>
                    <form id="reportForm">
                        ${reasonOptions}
                        <div class="mb-3 mt-3">
                            <label for="additionalInfo" class="form-label">Additional details (optional):</label>
                            <textarea class="form-control" id="additionalInfo" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" id="submitReport">Submit Report</button>
                </div>
            </div>
        </div>
    </div>`;
    
    // Remove any existing report modal
    $('#reportModal').remove();
    
    // Add the new modal to the DOM
    $('body').append(reportModalHtml);
    
    // Initialize the modal
    const reportModal = new bootstrap.Modal(document.getElementById('reportModal'));
    reportModal.show();
    
    // Handle the submit button
    $('#submitReport').on('click', function() {
        const reason = $('input[name="reportReason"]:checked').val();
        const details = $('#additionalInfo').val();
        
        axios.post(base_url + "/webapi/post/action", {
            post_id: postId,
            action: 'report',
            reason: reason,
            details: details
        })
        .then(response => {
            reportModal.hide();
            if (response.data.status === 200) {
                showAlert('success', 'Report Submitted', 'Thank you for reporting this post. We will review it shortly.');
            } else {
                showAlert('error', 'Error', response.data.message);
            }
        })
        .catch(error => {
            reportModal.hide();
            showAlert('error', 'Error', error.response?.data?.message || 'Failed to perform this action.');
        });
    });
}

function sharePost(postId, shareType, customText = '') {
    axios.post(base_url + "/webapi/post/action", {
        post_id: postId,
        action: 'share',
        share_type: shareType,
        shared_text: customText
    })
    .then(response => {
        if (response.data.status === 200) {
            // Update shares count in UI
            const sharesCount = response.data.data.shares_count;
            $(`#cardShareAction${postId}`).html(`<i class="bi bi-reply-fill flip-horizontal ps-1"></i> Share (${sharesCount})`);
            
            showAlert('success', 'Success', 'Post shared successfully');
            
            // If it's a share with text, reload the feed to show the new post
            if (shareType === 'with_text') {
                loadNewsFeed(response.data.data.new_post_id);
            }
        } else {
            showAlert('error', 'Error', response.data.message);
        }
    })
    .catch(error => {
        showAlert('error', 'Error', error.response?.data?.message || 'Failed to share this post.');
    });
}

function copyPostLink(postId) {
    // Create a temporary textarea to copy the link
    const tempTextArea = document.createElement('textarea');
    tempTextArea.value = `${window.location.origin}/post/${postId}`;
    document.body.appendChild(tempTextArea);
    tempTextArea.select();
    document.execCommand('copy');
    document.body.removeChild(tempTextArea);
    
    showAlert('success', 'Link Copied', 'Post link copied to clipboard');
}

function renderComment(comment, postId) {
    // Support both user and author properties in the API response
    const author = comment.user || comment.author;
    const timeAgo = formatTimeAgo(comment.created_at);
    // Default to false if is_mine is not provided
    const isMyComment = comment.is_mine === true;
    const commentId = comment.id;
    
    // Handle reaction state - default to no reaction if my_reaction is not provided
    const hasReacted = comment.my_reaction !== null && comment.my_reaction !== undefined;
    const reactionClass = hasReacted ? 'text-primary' : '';
    const reactionCount = comment.reactions || comment.likes_count || 0;
    
    // Use content field as per your API response
    const commentText = comment.content || comment.text || '';
    
    // Generate a unique badge if the comment is from the post author
    const authorBadge = comment.is_author ? 
        `<span class="badge bg-primary-soft text-primary fs-xs ms-2">Author</span>` : '';
    
    // Check if the comment has been edited
    const editedLabel = comment.is_edited ? 
        `<span class="text-muted fs-xs ms-2">(Edited)</span>` : '';
    
    let commentHtml = `
    <div class="comment d-flex mb-3" id="comment-${commentId}">
        <div class="avatar avatar-sm me-2">
            <a href="javascript:void(0)">
                <img class="avatar rounded-circle border" src="${author.avatar}" alt="${author.first_name} ${author.last_name}">
            </a>
        </div>
        <div class="comment-body rounded-3 p-0 w-100">
            <div class="comment-bubble bg-light p-3 rounded-4">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <div class="d-flex align-items-center">
                        <a href="javascript:void(0)" class="fw-semibold text-body text-decoration-none">${author.first_name} ${author.last_name}</a>
                        ${authorBadge}
                        ${editedLabel}
                    </div>
                    <small class="text-muted fs-xs">${timeAgo}</small>
                </div>
                <p class="mb-1 comment-text">${commentText}</p>
            </div>
            
            <div class="comment-actions d-flex align-items-center my-2 ps-2">
                <a href="javascript:void(0)" onclick="reactToComment(${commentId}, 'like', ${postId})" 
                   class="comment-action-btn ${reactionClass} me-3" data-bs-toggle="tooltip" title="Like">
                    <i class="bi ${hasReacted ? 'bi-hand-thumbs-up-fill' : 'bi-hand-thumbs-up'}"></i>
                    ${reactionCount > 0 ? `<span class="reaction-count">${reactionCount}</span>` : ''}
                </a>
                <a href="javascript:void(0)" onclick="replyToComment(${postId}, ${commentId})" 
                   class="comment-action-btn me-3" data-bs-toggle="tooltip" title="Reply">
                    <i class="bi bi-reply"></i> <span class="action-text">Reply</span>
                </a>
                ${isMyComment ? `
                <div class="dropdown comment-more-actions">
                    <a href="javascript:void(0)" class="comment-action-btn" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bi bi-three-dots"></i>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                        <li><a class="dropdown-item edit-comment-btn" href="javascript:void(0)" onclick="editComment(${commentId}, ${postId})">
                            <i class="bi bi-pencil pe-2"></i> Edit
                        </a></li>
                        <li><a class="dropdown-item delete-comment-btn" href="javascript:void(0)" onclick="deleteComment(${commentId}, ${postId})">
                            <i class="bi bi-trash pe-2"></i> Delete
                        </a></li>
                    </ul>
                </div>
                ` : ''}
            </div>`;
    
    // Render replies if they exist
    if (comment.replies && comment.replies.length > 0) {
        commentHtml += `<div class="replies ms-4 mt-3">`;
        comment.replies.forEach(reply => {
            const replyAuthor = reply.user || reply.author;
            const replyTimeAgo = formatTimeAgo(reply.created_at);
            const isMyReply = reply.is_mine === true;
            const replyId = reply.id;
            
            // Reaction states for reply
            const hasReplyReacted = reply.my_reaction !== null && reply.my_reaction !== undefined;
            const replyReactionClass = hasReplyReacted ? 'text-primary' : '';
            const replyReactionCount = reply.reactions || reply.likes_count || 0;
            const replyText = reply.content || reply.text || '';
            
            // Generate a unique badge if the reply is from the post author
            const replyAuthorBadge = reply.is_author ? 
                `<span class="badge bg-primary-soft text-primary fs-xs ms-2">Author</span>` : '';
            
            // Check if the reply has been edited
            const replyEditedLabel = reply.is_edited ? 
                `<span class="text-muted fs-xs ms-2">(Edited)</span>` : '';
            
            commentHtml += `
            <div class="reply d-flex mb-2" id="reply-${replyId}">
                <div class="avatar me-2">
                    <img class="avatar rounded-circle border" src="${replyAuthor.avatar}" alt="${replyAuthor.first_name} ${replyAuthor.last_name}">
                </div>
                <div class="reply-body w-100">
                    <div class="reply-bubble bg-light p-2 rounded-4">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <div class="d-flex align-items-center">
                                <a href="javascript:void(0)" class="fw-semibold text-body text-decoration-none">${replyAuthor.first_name} ${replyAuthor.last_name}</a>
                                ${replyAuthorBadge}
                                ${replyEditedLabel}
                            </div>
                            <small class="text-muted fs-xs">${replyTimeAgo}</small>
                        </div>
                        <p class="mb-1 reply-text">${replyText}</p>
                    </div>
                    
                    <div class="reply-actions d-flex align-items-center mt-1 ps-2">
                        <a href="javascript:void(0)" onclick="reactToComment(${replyId}, 'like', ${postId})" 
                           class="comment-action-btn ${replyReactionClass} me-3" data-bs-toggle="tooltip" title="Like">
                            <i class="bi ${hasReplyReacted ? 'bi-hand-thumbs-up-fill' : 'bi-hand-thumbs-up'}"></i>
                            ${replyReactionCount > 0 ? `<span class="reaction-count">${replyReactionCount}</span>` : ''}
                        </a>
                        ${isMyReply ? `
                        <div class="dropdown reply-more-actions">
                            <a href="javascript:void(0)" class="comment-action-btn" data-bs-toggle="dropdown" aria-expanded="false">
                                <i class="bi bi-three-dots"></i>
                            </a>
                            <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                                <li><a class="dropdown-item edit-reply-btn" href="javascript:void(0)" onclick="editComment(${replyId}, ${postId})">
                                    <i class="bi bi-pencil pe-2"></i> Edit
                                </a></li>
                                <li><a class="dropdown-item delete-reply-btn" href="javascript:void(0)" onclick="deleteComment(${replyId}, ${postId})">
                                    <i class="bi bi-trash pe-2"></i> Delete
                                </a></li>
                            </ul>
                        </div>
                        ` : ''}
                    </div>
                </div>
            </div>`;
        });
        commentHtml += `</div>`;
    }
    
    // Add reply form container
    commentHtml += `<div class="reply-form-container" id="reply-form-${commentId}" style="display:none;"></div>
        </div>
    </div>`;

    return commentHtml;
}

// Function to show comments for a post
function showComments(postId) {
    const commentsSection = $(`#comments-section-${postId}`);
    
    if (commentsSection.is(':visible')) {
        commentsSection.slideUp();
        return;
    }
    
    // Show loading indicator with nicer animation
    commentsSection.html(`
        <div class="text-center py-4">
            <div class="spinner-grow spinner-grow-sm text-primary mx-1" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <div class="spinner-grow spinner-grow-sm text-primary mx-1" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <div class="spinner-grow spinner-grow-sm text-primary mx-1" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2 text-muted">Loading comments...</p>
        </div>
    `);
    commentsSection.slideDown();
    
    // Fetch comments
    axios.post(base_url + "/webapi/post/comment-action", {
        post_id: postId,
        offset: 0,
        action: 'get',
        limit: 10
    })
    .then(response => {
        if (response.data.status === 200) {
            const comments = response.data.data;
            
            if (comments.length === 0) {
                commentsSection.html(`
                    <div class="text-center py-4">
                        <div class="empty-comments-icon mb-3">
                            <i class="bi bi-chat-square-text fs-1 text-muted"></i>
                        </div>
                        <p class="text-muted">No comments yet. Be the first to comment!</p>
                    </div>
                `);
                return;
            }
            
            let commentsHtml = `
            <div class="comments-header d-flex justify-content-between align-items-center mb-3">
                <h6 class="mb-0"><i class="bi bi-chat-square-text me-2"></i>Comments (${comments.length})</h6>
            </div>
            <div class="comments-list">`;
            
            // Render each comment
            comments.forEach(comment => {
                commentsHtml += renderComment(comment, postId);
            });
            
            commentsHtml += `</div>`;
            
            // Add load more button with improved styling
            if (comments.length >= 10) {
                commentsHtml += `
                <div class="text-center mt-3">
                    <button class="btn btn-sm btn-outline-primary rounded-pill load-more-comments" data-post-id="${postId}" data-offset="${comments.length}">
                        <i class="bi bi-chat-text me-1"></i> Load more comments
                    </button>
                </div>`;
            }
            
            commentsSection.html(commentsHtml);
            
            // Initialize tooltips
           // initTooltips();
        } else {
            commentsSection.html(`
                <div class="alert alert-danger m-3">
                    <i class="bi bi-exclamation-triangle-fill me-2"></i>
                    <span>${response.data.message}</span>
                </div>
            `);
        }
    })
    .catch(error => {
        
        commentsSection.html(`
            <div class="alert alert-danger m-3">
                <i class="bi bi-exclamation-triangle-fill me-2"></i>
                <span>Failed to load comments. Please try again.</span>
            </div>
        `);
    });
}

function renderReplies(comment) {
    let repliesHtml = `<div class="replies ms-4 mt-3">`;
    
    comment.replies.forEach(reply => {
        const author = reply.author;
        const timeAgo = formatTimeAgo(reply.created_at);
        const isMyReply = reply.is_mine;
        
        // Determine if user has reacted to this reply
        const hasReacted = reply.my_reaction !== null;
        const reactionClass = hasReacted ? 'text-primary' : '';
        
        repliesHtml += `
        <div class="reply d-flex mb-2" id="reply-${reply.id}">
            <div class="avatar me-2">
                <img class="avatar rounded-circle" src="${author.avatar}" alt="${author.first_name} ${author.last_name}">
            </div>
            <div class="reply-body bg-light rounded-3 p-2 w-100">
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <div>
                        <a href="#!" class="fw-bold text-body">${author.first_name} ${author.last_name}</a>
                    </div>
                    <small class="text-muted">${timeAgo}</small>
                </div>
                <p class="mb-1">${reply.text}</p>
                <div class="reply-actions mt-2 small">
                    <a href="javascript:void(0)" onclick="reactToComment(${reply.id}, 'like', ${postId})" class="text-reset me-3 ${reactionClass}">
                        <i class="bi ${hasReacted ? 'bi-hand-thumbs-up-fill' : 'bi-hand-thumbs-up'}"></i>
                        Like${reply.reactions > 0 ? ' · '+reply.reactions : ''}
                    </a>
                    ${isMyReply ? `<a href="javascript:void(0)" onclick="deleteComment(${reply.id}, ${postId})" class="text-reset">
                        <i class="bi bi-trash"></i> Delete
                    </a>` : ''}
                </div>
            </div>
        </div>`;
    });
    
    repliesHtml += `</div>`;
    return repliesHtml;
}


// Function to post a new comment or reply
function postComment(postId, text, parentId = null) {
    if (!text.trim()) return;
    
    // Clear the comment input
    $(`.comment-input[data-post-id="${postId}"]`).val('');
    
    axios.post(base_url + "/webapi/post/comment-action", {
        post_id: postId,
        action: 'add',
        content: text,
        parent_id: parentId
    })
    .then(response => {
        if (response.data.status === 200) {
            const newComment = response.data.data;
            
            if (parentId) {
                // If it's a reply, we need to refresh the entire comments section
                // because we need to show it under the parent comment
                showComments(postId);
                
                // Clear and hide the reply form
                $(`#reply-input-${parentId}`).val('');
                $(`#reply-form-${parentId}`).slideUp();
            } else {
                // If it's a new top-level comment
                const commentsSection = $(`#comments-section-${postId}`);
                
                // If comments section is not visible, make it visible
                if (!commentsSection.is(':visible')) {
                    commentsSection.slideDown();
                }
                
                // If this is the first comment, clear the "no comments" message
                if (commentsSection.find('.text-muted').length > 0 && 
                    commentsSection.find('.text-muted').text().includes('No comments yet')) {
                    commentsSection.empty();
                }
                
                // Add the new comment at the top
                if (commentsSection.find('.load-more-comments').length > 0) {
                    // If there's a load more button, insert before it
                    commentsSection.find('.load-more-comments').before(renderComment(newComment, postId));
                    
                    // Update the offset in the load more button
                    const loadMoreBtn = commentsSection.find('.load-more-comments');
                    const currentOffset = parseInt(loadMoreBtn.data('offset'));
                    loadMoreBtn.data('offset', currentOffset + 1);
                } else {
                    // Otherwise just append the comment
                    commentsSection.prepend(renderComment(newComment, postId));
                    
                    // Add load more button if it doesn't exist
                    commentsSection.append(`
                    <div class="text-center mt-2">
                        <button class="btn btn-sm btn-light rounded-pill load-more-comments" data-post-id="${postId}" data-offset="1">
                            <i class="bi bi-chat-text me-1"></i> Load more comments
                        </button>
                    </div>`);
                }
                
                // Update the comment count in the post
                const commentCountEl = $(`#post-${postId} .d-flex.small.text-muted div:first-child span:first-child`);
                const currentCount = parseInt(commentCountEl.text()) || 0;
                commentCountEl.text(currentCount + 1);
                
            }
        } else {
            showAlert('error', 'Error', response.data.message);
            $(`.comment-input[data-post-id="${postId}"]`).val(text);
        }
    })
    .catch(error => {
        
        $(`.comment-input[data-post-id="${postId}"]`).val(text);
        showAlert('error', 'Error', error.response?.data?.message || 'Failed to perform this action.');
    });
}


// Function to handle reply to a comment

// Function to handle reply to a comment
function replyToComment(postId, commentId) {
    const replyForm = $(`#reply-form-${commentId}`);
    
    if (replyForm.is(':visible')) {
        replyForm.slideUp();
        return;
    }
    
    const replyFormHtml = `
    <div class="d-flex mt-3 reply-form">
        <div class="avatar me-2">
            <img class="avatar rounded-circle border" src="${currentUserAvatar}" alt="${window.user ? window.user.name : 'Your Avatar'}">
        </div>
        <div class="w-100 position-relative">
            <div class="input-group">
                <textarea id="reply-input-${commentId}" class="form-control bg-light rounded-start-pill" rows="1" 
                  placeholder="Write a reply..." style="resize: none; border-right: none;"></textarea>
                <button class="btn btn-light rounded-end-pill border-start-0" onclick="postComment(${postId}, $('#reply-input-${commentId}').val(), ${commentId})">
                    <i class="bi bi-send-fill text-primary"></i>
                </button>
            </div>
            <div class="reply-tools position-absolute bottom-100 end-0 mb-1">
                <button class="btn btn-sm btn-light rounded-circle" title="Add emoji">
                    <i class="bi bi-emoji-smile"></i>
                </button>
            </div>
        </div>
    </div>`;
    
    replyForm.html(replyFormHtml).slideDown();
    
    // Auto-resize textarea as user types
    $(`#reply-input-${commentId}`).on('input', function() {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
    }).focus();
}




function reactToComment(commentId, reactionType, postId) {
    // Determine if this is a reply or main comment
    const isReply = $(`#reply-${commentId}`).length > 0;
    const action = isReply ? 'like-reply' : 'like';
    
    axios.post(base_url + "/webapi/post/comment-action", {
        comment_id: commentId,
        post_id: postId,
        action: action
    })
    .then(response => {
        if (response.data.status === 200) {
            // Toggle the visual state
            const likeLink = $(`#comment-${commentId} .comment-actions a:first-child, #reply-${commentId} .reply-actions a:first-child`);
            const icon = likeLink.find('i');
            
            // Toggle the visual state
            if (icon.hasClass('bi-hand-thumbs-up-fill')) {
                // Currently liked, so unlike
                likeLink.removeClass('text-primary');
                icon.removeClass('bi-hand-thumbs-up-fill').addClass('bi-hand-thumbs-up');
            } else {
                // Currently not liked, so like
                likeLink.addClass('text-primary');
                icon.removeClass('bi-hand-thumbs-up').addClass('bi-hand-thumbs-up-fill');
            }
            
            // Update the like count manually without refreshing the comments
            const reactionCountSpan = likeLink.find('.reaction-count');
            let currentCount = 0;
            
            if (reactionCountSpan.length > 0) {
                currentCount = parseInt(reactionCountSpan.text()) || 0;
            }
            
            // Toggle the count based on the visual state
            if (icon.hasClass('bi-hand-thumbs-up-fill')) {
                // Just liked, increment count
                currentCount += 1;
            } else {
                // Just unliked, decrement count
                currentCount = Math.max(0, currentCount - 1);
            }
            
            // Update the count display
            if (currentCount > 0) {
                if (reactionCountSpan.length > 0) {
                    reactionCountSpan.text(currentCount);
                } else {
                    likeLink.append(` <span class="reaction-count">${currentCount}</span>`);
                }
            } else {
                reactionCountSpan.remove();
            }
        } else {
            showAlert('error', 'Error', response.data.message);
        }
    })
    .catch(error => {
        showAlert('error', 'Error', error.response?.data?.message || 'Failed to perform this action.');
    });
}

function deleteComment(commentId, postId) {
    if (!confirm('Are you sure you want to delete this comment?')) {
        return;
    }
    
    // Determine if this is a reply or main comment
    const isReply = $(`#reply-${commentId}`).length > 0;
    const action = isReply ? 'delete-reply' : 'delete';
    
    axios.post(base_url + "/webapi/post/comment-action", {
        comment_id: commentId,
        post_id: postId,
        action: action
    })
    .then(response => {
        if (response.data.status === 200) {
            // Remove comment from UI
            $(`#comment-${commentId}, #reply-${commentId}`).fadeOut(300, function() {
                $(this).remove();
            });
        } else {
            showAlert('error', 'Error', response.data.message);
        }
    })
    .catch(error => {
        showAlert('error', 'Error', error.response?.data?.message || 'Failed to perform this action.');
    });
}

function shareWithText(postId) {
    // Show share modal with text input
    const shareModalHtml = `
    <div class="modal mt-4 fade" id="shareModal" tabindex="-1" aria-labelledby="shareModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="shareModalLabel">Share with Your Thoughts</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <textarea class="form-control" id="shareText" rows="3" placeholder="What's on your mind?"></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="submitShare">Share</button>
                </div>
            </div>
        </div>
    </div>`;
    
    // Remove any existing share modal
    $('#shareModal').remove();
    
    // Add the new modal to the DOM
    $('body').append(shareModalHtml);
    
    // Initialize the modal
    const shareModal = new bootstrap.Modal(document.getElementById('shareModal'));
    shareModal.show();
    
    // Handle the submit button
    $('#submitShare').on('click', function() {
        const text = $('#shareText').val();
        sharePost(postId, 'with_text', text);
        shareModal.hide();
    });
}

// Display nice alert messages
function showAlert(icon, title, text) {
    // Check if SweetAlert2 is available
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            icon: icon,
            title: title,
            text: text,
            timer: 3000,
            timerProgressBar: true
        });
    } else {
        // Fallback to myAlert if defined (from your original code)
        if (typeof myAlert !== 'undefined') {
            myAlert.fire({
                icon: icon,
                title: title,
                text: text
            });
        } else {
            // Last resort, use browser alert
            alert(`${title}: ${text}`);
        }
    }
}

$(document).ready(function() {
    loadNewsFeed(); // Load initial posts
    $(window).on("scroll", handleScroll); // Attach scroll event listener
    
    // Initialize tooltips
    initTooltips();
    
    // Load dashboard data for right sidebar
    //loadProfileCompletion();
    //loadUserGroups();
    //loadSuggestedUsers();
    
    // Initialize a variable for current user's avatar (you would get this from your backend)
    // This is used in reply forms - use window.user data if available
    window.currentUserAvatar = window.user ? window.user.avatar : ($(".navbar .user-avatar img").attr("src") || "../assets/images/avatar/user.jpg");
    
    // Handle reaction menu hover
    $(document).on("mouseenter", ".like_action", function() {
        $(this).find(".reaction-box").css("display", "flex");
        
        // Add show class to all reaction icons with a slight delay for animation effect
        const $icons = $(this).find(".reaction-icon");
        $icons.each(function(index) {
            const $icon = $(this);
            setTimeout(function() {
                $icon.addClass("show");
            }, index * 50); // Staggered animation
        });
    });
    
    // Add mouseenter event for the reaction box itself to prevent it from disappearing
   
    
    $(document).on("mouseleave", ".like_action", function() {
        const $box = $(this).find(".reaction-box");
        const $icons = $(this).find(".reaction-icon");
        
        // Check if mouse is over the reaction box
        if (!$box.is(":hover")) {
            // Remove show class from icons first
            $icons.removeClass("show");
            
            // Hide the box after a short delay to allow for animation
            setTimeout(function() {
                // Double check if mouse is still not over the box before hiding
                if (!$box.is(":hover")) {
                    $box.css("display", "none");
                }
            }, 200);
        }
    });
    
    // Add mouseleave event for the reaction box itself
    $(document).on("mouseleave", ".reaction-box", function() {
        const $box = $(this);
        const $icons = $box.find(".reaction-icon");
        
        // Remove show class from icons first
        $icons.removeClass("show");
        
        // Hide the box after a short delay to allow for animation
        setTimeout(function() {
            $box.css("display", "none");
        }, 200);
    });
    
    // Handle reaction click
    $(document).on("click", ".add_reaction", function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        const postId = $(this).closest(".post_card").attr("id").replace("post-", "");
        const reactionType = $(this).data("reactiontype");
        
        // Map reaction type numbers to reaction names
        const reactionMap = {
            "1": "like",
            "2": "love",
            "3": "haha",
            "4": "wow",
            "5": "sad",
            "6": "angry"
        };
        
        // Add a visual feedback effect
        const $icon = $(this);
        $icon.css("transform", "scale(1.5)");
        setTimeout(() => {
            $icon.css("transform", "");
            
            // Call the reaction API
            reactToPost(postId, reactionType);
            
            // Hide reaction box after selection with a nice transition
            const $reactionBox = $(this).closest(".reaction-box");
            const $icons = $reactionBox.find(".reaction-icon");
            
            // Animate icons out
            $icons.removeClass("show");
            
            // Hide the box after animation completes
            setTimeout(() => {
                $reactionBox.css("display", "none");
            }, 200);
        }, 150);
    });
    
    // Handle direct like button click (when not hovering to select reaction)
    $(document).on("click", ".first_action", function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        const postId = $(this).closest(".post_card").attr("id").replace("post-", "");
        //reactToPost(postId, "like");
    });
    
    
    // Initialize tooltips
    function initTooltips() {
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl, {
                delay: { show: 500, hide: 100 }
            });
        });
    }
    
    // Handle open image viewer
    window.openImageViewer = function(imageUrl) {
        // Create a modal to display the image in full size
        const viewerHtml = `
        <div class="modal fade" id="imageViewerModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-xl">
                <div class="modal-content bg-transparent border-0">
                    <div class="modal-body p-0 text-center">
                        <img src="${imageUrl}" class="img-fluid rounded" style="max-height: 90vh;" alt="Full size image">
                        <button type="button" class="btn-close bg-white position-absolute top-0 end-0 m-3" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                </div>
            </div>
        </div>`;
        
        // Remove any existing viewer
        $('#imageViewerModal').remove();
        
        // Add new viewer and show it
        $('body').append(viewerHtml);
        const modal = new bootstrap.Modal(document.getElementById('imageViewerModal'));
        modal.show();
    };




let mediaFiles = []; // Stores selected media
let selectedPrivacy = 1; // Default privacy: Public
let selectedFeeling = ""; // Stores user-selected feeling
let userLocation = ""; // Stores user's checked-in location

// Function to update media preview
function updateMediaPreview() {
    let previewArea = $("#preview-area");
    if(mediaFiles.length > 0){
        previewArea.html(""); // Clear previous previews
        previewArea.removeClass("d-none");
    }else{
        previewArea.addClass("d-none");
        return;
    }

    mediaFiles.forEach((file, index) => {
        let fileURL = URL.createObjectURL(file);
        let mediaType = "";
        let mediaElement = "";

        if (file.type.startsWith("image")) {
            mediaType = "image";
            mediaElement = `<img src="${fileURL}" class="rounded" width="100" height="100" alt="Preview">`;
        } else if (file.type.startsWith("video")) {
            mediaType = "video";
            mediaElement = `<video src="${fileURL}" class="rounded" width="100" height="100" controls></video>`;
        } else if (file.type.startsWith("audio")) {
            mediaType = "audio";
            mediaElement = `
                <div class="audio-preview rounded d-flex align-items-center justify-content-center" style="width: 100px; height: 100px; background: #f8f9fa; border: 2px dashed #dee2e6;">
                    <div class="text-center">
                        <i class="bi bi-music-note-beamed text-primary" style="font-size: 2rem;"></i>
                        <div class="small text-muted mt-1">${truncateMiddle(file.name, 25)}</div>
                    </div>
                </div>
            `;
        } else {
            // Generic file preview: show icon and name
            mediaType = "file";
            const ext = file.name.split('.').pop().toLowerCase();
            const isPdf = file.type === 'application/pdf' || ext === 'pdf';
            const icon = isPdf ? 'bi-file-earmark-pdf text-danger' : 'bi-file-earmark';
            mediaElement = `
                <div class="file-preview rounded d-flex align-items-center justify-content-center" style="width: 140px; height: 100px; background: #f8f9fa; border: 2px dashed #dee2e6;">
                    <div class="text-center px-2">
                        <i class="bi ${icon}" style="font-size: 2rem;"></i>
                        <div class="small text-muted mt-1 text-truncate" style="max-width:120px">${escapeHtml(truncateMiddle(file.name, 25))}</div>
                    </div>
                </div>
            `;
        }

        let mediaPreview = `
            <div class="preview-item position-relative d-inline-block me-2">
                ${mediaElement}
                <span class="remove-media bg-danger cursor-pointer pointer rounded-circle text-white text-center" style="position: absolute;top: -5px;right: -5px;width: 20px;height: 20px;"><i class="bi bi-x"></i></span>
            </div>
        `;
        previewArea.append(mediaPreview);
    });
}

// Advanced Emoji Picker
const emojiData = {
    smileys: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣', '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓', '🤗', '🤔', '🤭', '🤫', '🤥', '😶', '😐', '😑', '😯', '😦', '😧', '😮', '😲', '🥱', '😴', '🤤', '😪', '😵', '🤐', '🥴', '🤢', '🤮', '🤧', '😷', '🤒', '🤕'],
    animals: ['🐶', '🐱', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼', '🐨', '🐯', '🦁', '🐮', '🐷', '🐸', '🐵', '🙈', '🙉', '🙊', '🐒', '🐔', '🐧', '🐦', '🐤', '🐣', '🐥', '🦆', '🦅', '🦉', '🦇', '🐺', '🐗', '🐴', '🦄', '🐝', '🐛', '🦋', '🐌', '🐞', '🐜', '🦟', '🦗', '🕷️', '🕸️', '🦂', '🐢', '🐍', '🦎', '🦖', '🦕', '🐙', '🦑', '🦐', '🦞', '🦀', '🐡', '🐠', '🐟', '🐬', '🐳', '🐋', '🦈', '🐊', '🐅', '🐆', '🦓', '🦍', '🦧', '🐘', '🦛', '🦏', '🐪', '🐫', '🦙', '🦒', '🐃', '🐂', '🐄', '🐎', '🐖', '🐏', '🐑', '🦌', '🐕', '🐩', '🦮', '🐕‍🦺', '🐈', '🐈‍⬛', '🐓', '🦃', '🦚', '🦜', '🦢', '🦩', '🕊️', '🐇', '🦝', '🦨', '🦡', '🦫', '🦦', '🦥', '🐁', '🐀', '🐿️', '🦔'],
    food: ['🍎', '🍐', '🍊', '🍋', '🍌', '🍉', '🍇', '🍓', '🫐', '🍈', '🍒', '🍑', '🥭', '🍍', '🥥', '🥝', '🍅', '🥑', '🥦', '🥬', '🥒', '🌶️', '🫑', '🌽', '🥕', '🫒', '🧄', '🧅', '🥔', '🍠', '🥐', '🥯', '🍞', '🥖', '🥨', '🧀', '🥚', '🍳', '🧈', '🥞', '🧇', '🥓', '🥩', '🍗', '🍖', '🦴', '🌭', '🍔', '🍟', '🍕', '🥪', '🥙', '🧆', '🌮', '🌯', '🫔', '🥗', '🥘', '🫕', '🥫', '🍝', '🍜', '🍲', '🍛', '🍣', '🍱', '🥟', '🦪', '🍤', '🍙', '🍚', '🍘', '🍥', '🥠', '🥮', '🍢', '🍡', '🍧', '🍨', '🍦', '🥧', '🧁', '🍰', '🎂', '🍮', '🍭', '🍬', '🍫', '🍿', '🍪', '🌰', '🥜', '🍯', '🥛', '🍼', '🫖', '☕', '🍵', '🧃', '🥤', '🧋', '🍶', '🍺', '🍷', '🥂', '🥃', '🍸', '🍹', '🧉', '🍾', '🥄', '🍴', '🍽️', '🥣', '🥡', '🥢', '🧂'],
    activities: ['⚽', '🏀', '🏈', '⚾', '🥎', '🎾', '🏐', '🏉', '🥏', '🎱', '🪀', '🏓', '🏸', '🏒', '🏑', '🥍', '🏏', '🥅', '⛳', '🪁', '🏹', '🎣', '🤿', '🥊', '🥋', '🎽', '🛹', '🛷', '⛸️', '🥌', '🎿', '⛷️', '🏂', '🪂', '🏋️‍♀️', '🏋️', '🏋️‍♂️', '🤼‍♀️', '🤼', '🤼‍♂️', '🤸‍♀️', '🤸', '🤸‍♂️', '⛹️‍♀️', '⛹️', '⛹️‍♂️', '🤺', '🤾‍♀️', '🤾', '🤾‍♂️', '🏊‍♀️', '🏊', '🏊‍♂️', '🤽‍♀️', '🤽', '🤽‍♂️', '🚣‍♀️', '🚣', '🚣‍♂️', '🧗‍♀️', '🧗', '🧗‍♂️', '🚵‍♀️', '🚵', '🚵‍♂️', '🚴‍♀️', '🚴', '🚴‍♂️', '🏆', '🥇', '🥈', '🥉', '🏅', '🎖️', '🏵️', '🎗️', '🎫', '🎟️', '🎪', '🤹‍♀️', '🤹', '🤹‍♂️', '🎭', '🎨', '🎬', '🎤', '🎧', '🎼', '🎹', '🥁', '🪘', '🎷', '🎺', '🎸', '🪕', '🎻', '🎲', '♟️', '🎯', '🎳', '🎮', '🎰', '🧩', '🎨', '📱', '📲', '💻', '⌨️', '🖥️', '🖨️', '🖱️', '🖲️', '🕹️', '🎮', '🎰', '🎲', '🧩', '🎨', '🎭', '🎪', '🎟️', '🎫', '🎖️', '🏆', '🏅', '🥇', '🥈', '🥉'],
    travel: ['✈️', '🛩️', '🛫', '🛬', '🪂', '💺', '🚁', '🚟', '🚠', '🚡', '🛰️', '🚀', '🛸', '🚁', '🚂', '🚃', '🚄', '🚅', '🚆', '🚇', '🚈', '🚉', '🚊', '🚝', '🚞', '🚋', '🚌', '🚍', '🚎', '🚐', '🚑', '🚒', '🚓', '🚔', '🚕', '🚖', '🚗', '🚘', '🚙', '🚚', '🚛', '🚜', '🏎️', '🏍️', '🛵', '🦽', '🦼', '🛴', '🚲', '🛶', '⛵', '🚤', '🛥️', '🛳️', '⛴️', '🚢', '🚁', '🚟', '🚠', '🚡', '🛰️', '🚀', '🛸', '🚁', '🚂', '🚃', '🚄', '🚅', '🚆', '🚇', '🚈', '🚉', '🚊', '🚝', '🚞', '🚋', '🚌', '🚍', '🚎', '🚐', '🚑', '🚒', '🚓', '🚔', '🚕', '🚖', '🚗', '🚘', '🚙', '🚚', '🚛', '🚜', '🏎️', '🏍️', '🛵', '🦽', '🦼', '🛴', '🚲', '🛶', '⛵', '🚤', '🛥️', '🛳️', '⛴️', '🚢'],
    objects: ['💡', '🔦', '🕯️', '🪔', '🧯', '🛢️', '💸', '💵', '💴', '💶', '💷', '🪙', '💰', '💳', '💎', '⚖️', '🪜', '🧰', '🪛', '🔧', '🔨', '⚒️', '🛠️', '⛏️', '🪚', '🔩', '⚙️', '🪤', '🧲', '⛓️', '🪝', '🧿', '🔫', '💣', '🪃', '🏹', '🛡️', '🪄', '🔮', '🧿', '📿', '🧸', '🪆', '🪅', '🪩', '🪩', '🎈', '🎉', '🎊', '🎋', '🎍', '🎎', '🎏', '🎐', '🎀', '🎁', '🪄', '🧿', '📿', '🧸', '🪆', '🪅', '🪩', '🪩', '🎈', '🎉', '🎊', '🎋', '🎍', '🎎', '🎏', '🎐', '🎀', '🎁', '🪄', '🧿', '📿', '🧸', '🪆', '🪅', '🪩', '🪩', '🎈', '🎉', '🎊', '🎋', '🎍', '🎎', '🎏', '🎐', '🎀', '🎁'],
    symbols: ['❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '🤎', '💔', '❣️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟', '☮️', '✝️', '☪️', '🕉️', '☸️', '✡️', '🔯', '🕎', '☯️', '☦️', '🛐', '⛎', '♈', '♉', '♊', '♋', '♌', '♍', '♎', '♏', '♐', '♑', '♒', '♓', '🆔', '⚛️', '🉑', '☢️', '☣️', '📴', '📳', '🈶', '🈚', '🈸', '🈺', '🈷️', '✴️', '🆚', '💮', '🉐', '㊙️', '㊗️', '🈴', '🈵', '🈹', '🈲', '🅰️', '🅱️', '🆎', '🆑', '🅾️', '🆘', '❌', '⭕', '🛑', '⛔', '📛', '🚫', '💯', '💢', '♨️', '🚷', '🚯', '🚳', '🚱', '🔞', '📵', '🚭', '❗', '❕', '❓', '❔', '‼️', '⁉️', '🔅', '🔆', '〽️', '⚠️', '🚸', '🔱', '⚜️', '🔰', '♻️', '✅', '🈯', '💹', '❇️', '✳️', '❎', '🌐', '💠', 'Ⓜ️', '🌀', '💤', '🏧', '🚾', '♿', '🅿️', '🛗', '🛂', '🛃', '🛄', '🛅', '🚹', '🚺', '🚼', '🚻', '🚮', '🎦', '📶', '🈁', '🔣', 'ℹ️', '🔤', '🔡', '🔠', '🆖', '🆗', '🆙', '🆒', '🆕', '🆓', '0️⃣', '1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', '🔟', '🔢', '#️⃣', '*️⃣', '⏏️', '▶️', '⏸️', '⏯️', '⏹️', '⏺️', '⏭️', '⏮️', '⏩', '⏪', '⏫', '⏬', '◀️', '🔼', '🔽', '➡️', '⬅️', '⬆️', '⬇️', '↗️', '↘️', '↙️', '↖️', '↕️', '↔️', '↪️', '↩️', '⤴️', '⤵️', '🔀', '🔁', '🔂', '🔄', '🔃', '🎵', '🎶', '➕', '➖', '➗', '✖️', '♾️', '💲', '💱', '™️', '©️', '®️', '👁️‍🗨️', '🔚', '🔙', '🔛', '🔝', '🔜', '〰️', '➰', '➿', '✔️', '☑️', '🔘', '🔴', '🟠', '🟡', '🟢', '🔵', '🟣', '⚫', '⚪', '🟤', '🔺', '🔻', '🔸', '🔹', '🔶', '🔷', '🔳', '🔲', '▪️', '▫️', '◾', '◽', '◼️', '◻️', '🟥', '🟧', '🟨', '🟩', '🟦', '🟪', '⬛', '⬜', '🟫', '🔈', '🔇', '🔉', '🔊', '🔔', '🔕', '📣', '📢', '💬', '💭', '🗯️', '♠️', '♣️', '♥️', '♦️', '🃏', '🎴', '🀄', '🕐', '🕑', '🕒', '🕓', '🕔', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕛', '🕜', '🕝', '🕞', '🕟', '🕠', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦', '🕧'],
    flags: ['🏁', '🚩', '🎌', '🏴', '🏳️', '🏳️‍🌈', '🏴‍☠️', '🇦🇨', '🇦🇩', '🇦🇫', '🇦🇬', '🇦🇷', '🇦🇲', '🇦🇼', '🇦🇺', '🇦🇹', '🇦🇿', '🇧🇸', '🇧🇭', '🇧🇩', '🇧🇯', '🇧🇲', '🇧🇳', '🇧🇴', '🇧🇶', '🇧🇷', '🇧🇸', '🇧🇹', '🇧🇻', '🇧🇼', '🇧🇾', '🇧🇿', '🇨🇦', '🇨🇨', '🇨🇩', '🇨🇫', '🇨🇬', '🇨🇭', '🇨🇮', '🇨🇰', '🇨🇱', '🇨🇲', '🇨🇳', '🇨🇴', '🇨🇵', '🇨🇷', '🇨🇺', '🇨🇻', '🇨🇼', '🇨🇽', '🇨🇾', '🇨🇿', '🇩🇪', '🇩🇯', '🇩🇰', '🇩🇲', '🇩🇴', '🇩🇿', '🇪🇨', '🇪🇪', '🇪🇬', '🇪🇭', '🇪🇷', '🇪🇸', '🇪🇹', '🇪🇺', '🇫🇮', '🇫🇯', '🇫🇰', '🇫🇲', '🇫🇴', '🇫🇷', '🇬🇦', '🇬🇧', '🇬🇩', '🇬🇪', '🇬🇫', '🇬🇬', '🇬🇭', '🇬🇮', '🇬🇱', '🇬🇲', '🇬🇳', '🇬🇵', '🇬🇶', '🇬🇷', '🇬🇸', '🇬🇹', '🇬🇺', '🇬🇼', '🇬🇾', '🇭🇰', '🇭🇲', '🇭🇳', '🇭🇷', '🇭🇹', '🇭🇺', '🇮🇩', '🇮🇪', '🇮🇱', '🇮🇲', '🇮🇳', '🇮🇴', '🇮🇶', '🇮🇷', '🇮🇸', '🇮🇹', '🇯🇪', '🇯🇲', '🇯🇴', '🇯🇵', '🇰🇪', '🇰🇬', '🇰🇭', '🇰🇮', '🇰🇲', '🇰🇳', '🇰🇵', '🇰🇷', '🇰🇼', '🇰🇾', '🇰🇿', '🇱🇦', '🇱🇧', '🇱🇨', '🇱🇮', '🇱🇰', '🇱🇷', '🇱🇸', '🇱🇹', '🇱🇺', '🇱🇻', '🇱🇾', '🇲🇦', '🇲🇨', '🇲🇩', '🇲🇪', '🇲🇫', '🇲🇬', '🇲🇭', '🇲🇰', '🇲🇱', '🇲🇲', '🇲🇳', '🇲🇴', '🇲🇵', '🇲🇶', '🇲🇷', '🇲🇸', '🇲🇹', '🇲🇺', '🇲🇻', '🇲🇼', '🇲🇽', '🇲🇾', '🇲🇿', '🇳🇦', '🇳🇨', '🇳🇪', '🇳🇫', '🇳🇬', '🇳🇮', '🇳🇱', '🇳🇴', '🇳🇵', '🇳🇷', '🇳🇺', '🇳🇿', '🇴🇲', '🇵🇦', '🇵🇪', '🇵🇫', '🇵🇬', '🇵🇭', '🇵🇰', '🇵🇱', '🇵🇲', '🇵🇳', '🇵🇷', '🇵🇸', '🇵🇹', '🇵🇼', '🇵🇾', '🇶🇦', '🇷🇪', '🇷🇴', '🇷🇸', '🇷🇺', '🇷🇼', '🇸🇦', '🇸🇧', '🇸🇨', '🇸🇩', '🇸🇪', '🇸🇬', '🇸🇭', '🇸🇮', '🇸🇯', '🇸🇰', '🇸🇱', '🇸🇲', '🇸🇳', '🇸🇴', '🇸🇷', '🇸🇸', '🇸🇹', '🇸🇻', '🇸🇽', '🇸🇾', '🇸🇿', '🇹🇦', '🇹🇨', '🇹🇩', '🇹🇯', '🇹🇰', '🇹🇱', '🇹🇲', '🇹🇳', '🇹🇴', '🇹🇷', '🇹🇹', '🇹🇻', '🇹🇼', '🇹🇿', '🇺🇦', '🇺🇬', '🇺🇲', '🇺🇳', '🇺🇸', '🇺🇾', '🇺🇿', '🇻🇦', '🇻🇨', '🇻🇪', '🇻🇬', '🇻🇮', '🇻🇳', '🇻🇺', '🇼🇫', '🇼🇸', '🇾🇪', '🇾🇹', '🇿🇦', '🇿🇲', '🇿🇼']
};

let currentEmojiCategory = 'smileys';

// Initialize emoji picker
function initEmojiPicker() {
    loadEmojis('smileys');
    
    // Handle category switching
    $('.emoji-category').on('click', function() {
        $('.emoji-category').removeClass('active');
        $(this).addClass('active');
        currentEmojiCategory = $(this).data('category');
        loadEmojis(currentEmojiCategory);
    });
    
    // Handle emoji search
    $('#emojiSearch').on('input', function() {
        const searchTerm = $(this).val().toLowerCase();
        filterEmojis(searchTerm);
    });
}

function loadEmojis(category) {
    const emojiGrid = $('#emojiGrid');
    emojiGrid.empty();
    
    emojiData[category].forEach(emoji => {
        emojiGrid.append(`
            <button class="emoji-item" data-emoji="${emoji}">
                ${emoji}
            </button>
        `);
    });
}

function filterEmojis(searchTerm) {
    const emojiGrid = $('#emojiGrid');
    emojiGrid.empty();
    
    Object.values(emojiData).flat().forEach(emoji => {
        if (emoji.includes(searchTerm) || searchTerm === '') {
            emojiGrid.append(`
                <button class="emoji-item" data-emoji="${emoji}">
                    ${emoji}
                </button>
            `);
        }
    });
}

// Handle emoji button click
$("#emojiButton").on("click", function() {
    const modal = new bootstrap.Modal(document.getElementById('emojiPickerModal'));
    modal.show();
});

// Handle emoji selection
$(document).on('click', '.emoji-item', function() {
    const emoji = $(this).data('emoji');
    
    // Check if we're inserting into a comment input
    if (window.currentCommentInput && window.currentCommentInput.length > 0) {
        const commentInput = window.currentCommentInput;
        const cursorPos = commentInput[0].selectionStart;
        const textBefore = commentInput.val().substring(0, cursorPos);
        const textAfter = commentInput.val().substring(cursorPos);
        commentInput.val(textBefore + emoji + textAfter);
        commentInput.focus();
        
        // Clear the stored comment input
        window.currentCommentInput = null;
        window.currentCommentPostId = null;
    } else {
        // Default to post input
        const textarea = $('#postInput');
        const cursorPos = textarea[0].selectionStart;
        const textBefore = textarea.val().substring(0, cursorPos);
        const textAfter = textarea.val().substring(cursorPos);
        textarea.val(textBefore + emoji + textAfter);
        textarea.focus();
    }
    
    // Close modal
    const modal = bootstrap.Modal.getInstance(document.getElementById('emojiPickerModal'));
    modal.hide();
});

// Handle comment emoji button click
$(document).on('click', '.comment-emoji-btn', function() {
    const commentInput = $(this).closest('.comment-input-container').find('.comment-input');
    const postId = commentInput.data('post-id');
    
    // Store the target input for emoji insertion
    window.currentCommentInput = commentInput;
    window.currentCommentPostId = postId;
    
    // Show emoji picker modal
    const modal = new bootstrap.Modal(document.getElementById('emojiPickerModal'));
    modal.show();
});


// Initialize emoji picker when document is ready
$(document).ready(function() {
    initEmojiPicker();
    
    // Debug: Check if color post button exists
    // Check colored post elements
    if ($('#createColorPost').length === 0) {
        console.warn("Color post button not found");
    }
    // Colored post elements check
    if ($('#colorPostSection').length === 0) {
        console.warn("Color post section not found");
    }
    if ($('#previewContent').length === 0) {
        console.warn("Preview content not found");
    }
});

// Handle media upload
$("#addPhotos, #addVideo").on("click", function () {
    let inputType = $(this).attr("id") === "addPhotos" ? "image/*" : "video/*";
    let maxFiles = $(this).attr("id") === "addPhotos" ? 10 : 1; // Max 10 images, 1 video
    
    let inputFile = $("<input>").attr({
        type: "file",
        accept: inputType,
        multiple: $(this).attr("id") === "addPhotos"
    });

    inputFile.on("change", function (event) {
        let files = event.target.files;
        
        // Check file count
        if (files.length > maxFiles) {
            myAlert.fire({
                icon: 'warning',
                title: 'Too Many Files',
                text: `You can only upload ${maxFiles} ${$(this).attr("id") === "addPhotos" ? "images" : "video"} at a time.`
            });
            return;
        }
        
        // Check file sizes (max 10MB per file)
        let totalSize = 0;
        for (let i = 0; i < files.length; i++) {
            totalSize += files[i].size;
            if (files[i].size > 10 * 1024 * 1024) { // 10MB
                myAlert.fire({
                    icon: 'error',
                    title: 'File Too Large',
                    text: `${files[i].name} is too large. Maximum file size is 10MB.`
                });
                return;
            }
        }
        
        // Add files to mediaFiles array
        $.each(files, function (_, file) {
            mediaFiles.push(file);
        });
        updateMediaPreview();
    });

    inputFile.trigger("click");
});

// Handle audio upload
$(document).on("click", "#addAudio", function () {
    let inputFile = $("<input>").attr({
        type: "file",
        accept: "audio/*",
        multiple: false
    });

    inputFile.on("change", function (event) {
        let files = event.target.files;
        
        if (files.length === 0) return;
        
        let file = files[0];
        
        // Check file size (max 25MB for audio)
        if (file.size > 25 * 1024 * 1024) { // 25MB
            myAlert.fire({
                icon: 'error',
                title: 'File Too Large',
                text: `${file.name} is too large. Maximum audio file size is 25MB.`
            });
            return;
        }
        
        // Check if it's a valid audio file
        if (!file.type.startsWith("audio/")) {
            myAlert.fire({
                icon: 'error',
                title: 'Invalid File Type',
                text: 'Please select a valid audio file (MP3, WAV, M4A, etc.).'
            });
            return;
        }
        
        // Add audio file to mediaFiles array
        mediaFiles.push(file);
        updateMediaPreview();
    });

    inputFile.trigger("click");
});

// Remove media from preview
$(document).on("click", ".remove-media", function () {
    let index = $(this).data("index");
    mediaFiles.splice(index, 1); // Remove from array
    updateMediaPreview(); // Refresh preview
});

// Handle privacy selection
$(".dropdown-menu a").on("click", function () {
    selectedPrivacy = $(this).data("privacy");
    $("#privacyDropdown span").text($(this).text().trim());
});

// Advanced Feeling Selection
const feelingOptionsData = {
    feeling: {
        title: "How are you feeling?",
        options: [
            { text: "Happy", emoji: "😊", color: "text-success" },
            { text: "Loved", emoji: "🥰", color: "text-danger" },
            { text: "Sad", emoji: "😢", color: "text-primary" },
            { text: "Very sad", emoji: "😭", color: "text-primary" },
            { text: "Angry", emoji: "😡", color: "text-danger" },
            { text: "Confused", emoji: "😕", color: "text-warning" },
            { text: "Hot", emoji: "🥵", color: "text-danger" },
            { text: "Broken", emoji: "💔", color: "text-secondary" },
            { text: "Expressionless", emoji: "😐", color: "text-muted" },
            { text: "Cool", emoji: "😎", color: "text-info" },
            { text: "Funny", emoji: "😂", color: "text-warning" },
            { text: "Tired", emoji: "😴", color: "text-secondary" },
            { text: "Lovely", emoji: "😍", color: "text-danger" },
            { text: "Blessed", emoji: "🙏", color: "text-success" },
            { text: "Shocked", emoji: "😱", color: "text-warning" },
            { text: "Sleepy", emoji: "😪", color: "text-secondary" },
            { text: "Pretty", emoji: "😊", color: "text-danger" },
            { text: "Bored", emoji: "😑", color: "text-muted" }
        ]
    },
    traveling: {
        title: "Where are you traveling?",
        options: [],
        custom: true
    },
    watching: {
        title: "What are you watching?",
        options: [],
        custom: true
    },
    listening: {
        title: "What are you listening to?",
        options: [],
        custom: true
    }
};

// Handle feeling button click
$(document).on("click", "#addFeeling", function () {
    // Show posting detail section
    $('.posting-detail').slideDown(300);
    
    // Show feeling section
    $('#feelingSection').slideDown(300);
    $('#feelingSubOptions').hide();
    $('#feelingOptionsGrid').empty();
    
    // Hide other sections
    $('#pollSection').slideUp(300);
    $('#locationSection').slideUp(300);
    $('#colorPostSection').slideUp(300);
});

// Handle colored post button click
$(document).on("click", "#createColorPost", function () {
    // Show posting detail section
    $('.posting-detail').slideDown(300);
    
    // Show colored post section
    $('#colorPostSection').slideDown(300);
    
    // Hide other sections
    $('#feelingSection').slideUp(300);
    $('#pollSection').slideUp(300);
    $('#locationSection').slideUp(300);
    $('#gifSection').slideUp(300);
    
    // Initialize colored post functionality
    initColoredPost();
});

// Handle GIF button click
$(document).on("click", "#addGif", function () {
    // Show posting detail section
    $('.posting-detail').slideDown(300);
    
    // Show GIF section
    $('#gifSection').slideDown(300);
    
    // Hide other sections
    $('#feelingSection').slideUp(300);
    $('#pollSection').slideUp(300);
    $('#locationSection').slideUp(300);
    $('#colorPostSection').slideUp(300);
    $('#voiceNoteSection').slideUp(300);
    
    // Initialize GIF functionality
    initGifSection();
});

// Handle Voice Note button click
$(document).on("click", "#addVoiceNote", function () {
    // Show posting detail section
    $('.posting-detail').slideDown(300);
    
    // Show Voice Note section
    $('#voiceNoteSection').slideDown(300);
    
    // Hide other sections
    $('#feelingSection').slideUp(300);
    $('#pollSection').slideUp(300);
    $('#locationSection').slideUp(300);
    $('#colorPostSection').slideUp(300);
    $('#gifSection').slideUp(300);
    $('#fileUploadSection').slideUp(300);
    
    // Initialize Voice Note functionality
    initVoiceNoteSection();
});

// Handle File Upload button click
$(document).on("click", "#addFile", function () {
    // Show posting detail section
    $('.posting-detail').slideDown(300);
    
    // Show File Upload section
    $('#fileUploadSection').slideDown(300);
    
    // Hide other sections
    $('#feelingSection').slideUp(300);
    $('#pollSection').slideUp(300);
    $('#locationSection').slideUp(300);
    $('#colorPostSection').slideUp(300);
    $('#gifSection').slideUp(300);
    $('#voiceNoteSection').slideUp(300);
    $('#tagPeopleSection').slideUp(300);
    
    // Initialize File Upload functionality
    initFileUploadSection();
});

// Handle Tag People button click
$(document).on("click", "#tagPeople", function () {
    // Show posting detail section
    $('.posting-detail').slideDown(300);
    
    // Show Tag People section
    $('#tagPeopleSection').slideDown(300);
    
    // Hide other sections
    $('#feelingSection').slideUp(300);
    $('#pollSection').slideUp(300);
    $('#locationSection').slideUp(300);
    $('#colorPostSection').slideUp(300);
    $('#gifSection').slideUp(300);
    $('#voiceNoteSection').slideUp(300);
    $('#fileUploadSection').slideUp(300);
    
    // Initialize Tag People functionality
    initTagPeopleSection();
});

// Handle Post to Page button click
$(document).on("click", "#postToPage", async function () {
    try {
        const resp = await axios.get(base_url + '/webapi/page/user-pages');
        const pages = resp.data && resp.data.data ? resp.data.data : [];
        const options = pages.map(p => ({ id: p.id, name: p.page_title, cover: p.cover }));
        openTargetSelectModal('Select a Page', options, function (selectedId) {
            $('#selectedPageId').val(selectedId);
            $('#postType').val('page_post');
            showTargetBadge('page', options.find(o => o.id == selectedId));
        });
    } catch (e) {
        myAlert.fire({ icon: 'error', title: 'Failed', text: 'Could not load your pages' });
    }
});

// Handle Post to Group button click
$(document).on("click", "#postToGroup", async function () {
    try {
        const resp = await axios.get(base_url + '/webapi/groups/user-groups');
        const data = resp.data && resp.data.data ? resp.data.data : [];
        const groups = Array.isArray(data) ? data : (data.data || []);
        const options = groups.map(g => ({ id: g.id, name: g.name, cover: g.cover_image }));
        openTargetSelectModal('Select a Group', options, function (selectedId) {
            $('#selectedGroupId').val(selectedId);
            $('#postType').val('group_post');
            showTargetBadge('group', options.find(o => o.id == selectedId));
        });
    } catch (e) {
        myAlert.fire({ icon: 'error', title: 'Failed', text: 'Could not load your groups' });
    }
});

function openTargetSelectModal(title, items, onSelect) {
    const modalId = 'targetSelectModal';
    const list = (items || []).map(i => `
        <a href="#" class="list-group-item list-group-item-action d-flex align-items-center" data-id="${i.id}">
            <img src="${i.cover || '/assets/images/placeholder/cover.png'}" class="rounded me-2" width="36" height="36" alt="">
            <span class="fw-semibold">${escapeHtml(i.name || '')}</span>
        </a>`).join('');
    const html = `
    <div class="modal fade" id="${modalId}" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">${escapeHtml(title)}</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="list-group" id="targetSelectList">
              ${list || '<div class="text-muted small">No items found</div>'}
            </div>
          </div>
        </div>
      </div>
    </div>`;
    const existing = document.getElementById(modalId);
    if (existing) existing.remove();
    document.body.insertAdjacentHTML('beforeend', html);
    const modal = new bootstrap.Modal(document.getElementById(modalId));
    modal.show();
    $(document).off('click', '#targetSelectList .list-group-item').on('click', '#targetSelectList .list-group-item', function (e) {
        e.preventDefault();
        const id = $(this).data('id');
        modal.hide();
        if (typeof onSelect === 'function') onSelect(id);
    });
}

function showTargetBadge(type, item) {
    $('.target-badge').remove();
    const label = type === 'page' ? 'Posting to page' : 'Posting in group';
    const name = escapeHtml(item && (item.name || item.title) ? (item.name || item.title) : (type === 'page' ? 'Page' : 'Group'));
    const badge = `
        <div class="target-badge d-inline-flex align-items-center bg-light rounded-pill px-3 py-1 me-2 mb-2">
            <i class="bi ${type === 'page' ? 'bi-flag' : 'bi-people'} text-primary me-2"></i>
            <div class="small">${label}: <strong>${name}</strong></div>
            <button type="button" class="btn-close btn-close-sm ms-2" onclick="clearTargetSelection('${type}')"></button>
        </div>`;
    $('.post-input-container').append(badge);
}

function clearTargetSelection(type) {
    if (type === 'page') {
        $('#selectedPageId').val('');
    } else if (type === 'group') {
        $('#selectedGroupId').val('');
    }
    // Reset to normal post if neither selected
    if (!$('#selectedPageId').val() && !$('#selectedGroupId').val()) {
        $('#postType').val('post');
    }
    $('.target-badge').remove();
}

// Close feeling section
$(document).on("click", "#closeFeeling", function () {
    $('#feelingSection').slideUp(300);
    resetFeelingSelection();
    
    // Hide posting detail if no other sections are open
    if (!$('#pollSection').is(':visible') && !$('#locationSection').is(':visible')) {
        $('.posting-detail').slideUp(300);
    }
});

// Handle feeling category selection
$(document).on("click", ".feeling-category", function () {
    const category = $(this).data('category');
    const categoryData = feelingOptionsData[category];
    
    // Remove active class from all categories
    $('.feeling-category').removeClass('active');
    // Add active class to clicked category
    $(this).addClass('active');
    
    $('#feeling-category').val(category);
    $('#feelingSubTitle').text(categoryData.title);
    
    if (categoryData.custom) {
        // Show custom input
        $('#feelingOptionsGrid').html(`
            <div class="custom-feeling-input p-3">
                <input type="text" class="form-control" id="customFeelingInput" 
                       placeholder="${categoryData.title}" maxlength="50">
                <div class="mt-2">
                    <button type="button" class="btn btn-primary btn-sm" id="saveCustomFeeling">
                        Save
                    </button>
                    <button type="button" class="btn btn-secondary btn-sm" id="cancelCustomFeeling">
                        Cancel
                    </button>
                </div>
            </div>
        `);
    } else {
        // Show predefined options
        let optionsHtml = '';
        categoryData.options.forEach(option => {
            optionsHtml += `
                <div class="feeling-option" data-feeling="${option.text}">
                    <div class="feeling-option-content">
                        <span class="feeling-emoji ${option.color}">${option.emoji}</span>
                        <span class="feeling-text">${option.text}</span>
                    </div>
                </div>
            `;
        });
        $('#feelingOptionsGrid').html(optionsHtml);
    }
    
    $('#feelingSubOptions').slideDown(300);
});

// Handle feeling option selection
$(document).on("click", ".feeling-option", function () {
    const feeling = $(this).data('feeling');
    $('#feeling-description').val(feeling);
    
    // Show selected feeling in the post input area
    showSelectedFeeling(feeling);
    
    // Hide feeling section
    $('#feelingSection').slideUp(300);
});

// Handle custom feeling input
$(document).on("click", "#saveCustomFeeling", function () {
    const customFeeling = $('#customFeelingInput').val().trim();
    if (customFeeling) {
        $('#feeling-description').val(customFeeling);
        showSelectedFeeling(customFeeling);
        $('#feelingSection').slideUp(300);
    }
});

$(document).on("click", "#cancelCustomFeeling", function () {
    $('#feelingSubOptions').slideUp(300);
});

function showSelectedFeeling(feeling) {
    const category = $('#feeling-category').val();
    let emoji = '';
    
    // Get emoji based on category
    if (category === 'feeling') {
        const feelingOption = feelingOptionsData.feeling.options.find(opt => opt.text === feeling);
        emoji = feelingOption ? feelingOption.emoji : '😊';
    } else {
        emoji = category === 'traveling' ? '✈️' : category === 'watching' ? '📺' : '🎵';
    }
    
    // Add feeling badge to post input area
    const feelingBadge = `
        <div class="selected-feeling-badge d-inline-flex align-items-center bg-light rounded-pill px-3 py-1 me-2 mb-2">
            <span class="me-2">${emoji}</span>
            <span class="feeling-text">${feeling}</span>
            <button type="button" class="btn-close btn-close-sm ms-2" onclick="removeSelectedFeeling()"></button>
        </div>
    `;
    
    // Remove existing feeling badge
    $('.selected-feeling-badge').remove();
    
    // Add new feeling badge after textarea
    $('#postInput').after(feelingBadge);
}

// Colored Post Variables
let selectedBackgroundColor = '#ffffff';
let selectedTextColor = '#000000';
let selectedFontSize = 'normal';

// Initialize Colored Post Functionality
function initColoredPost() {
    // Set default values
    selectedBackgroundColor = '#ffffff';
    selectedTextColor = '#000000';
    selectedFontSize = 'normal';
    
    // Set default selections
    $('#backgroundColors .color-option[data-color="#ffffff"]').addClass('selected');
    $('#textColors .color-option[data-color="#000000"]').addClass('selected');
    $('.font-size-btn[data-size="normal"]').addClass('active');
    
    // Update preview
    updateColoredPostPreview();
    
    // Add colored post class to textarea
    $('#postInput').addClass('colored-post');
    
    // Update textarea styling
    updateTextareaStyling();
}

// Handle background color selection
$(document).on('click', '#backgroundColors .color-option', function() {
    const color = $(this).data('color');
    const textColor = $(this).data('text-color');
    
    selectedBackgroundColor = color;
    if (textColor) {
        selectedTextColor = textColor;
        // Update text color selection
        $('#textColors .color-option').removeClass('selected');
        $(`#textColors .color-option[data-color="${textColor}"]`).addClass('selected');
    }
    
    // Update UI
    $('#backgroundColors .color-option').removeClass('selected');
    $(this).addClass('selected');
    
    // Update preview and textarea
    updateColoredPostPreview();
    updateTextareaStyling();
});

// Handle text color selection
$(document).on('click', '#textColors .color-option', function() {
    const color = $(this).data('color');
    selectedTextColor = color;
    
    // Update UI
    $('#textColors .color-option').removeClass('selected');
    $(this).addClass('selected');
    
    // Update preview and textarea
    updateColoredPostPreview();
    updateTextareaStyling();
});

// Handle font size selection
$(document).on('click', '.font-size-btn', function() {
    const size = $(this).data('size');
    selectedFontSize = size;
    
    // Update UI
    $('.font-size-btn').removeClass('active');
    $(this).addClass('active');
    
    // Update preview and textarea
    updateColoredPostPreview();
    updateTextareaStyling();
});

// Update colored post preview
function updateColoredPostPreview() {
    const previewContent = $('#previewContent');
    const postText = $('#postInput').val() || 'Preview your colored post here...';
    
    if (previewContent.length > 0) {
        previewContent.css({
            'background-color': selectedBackgroundColor,
            'color': selectedTextColor,
            'font-size': getFontSize(selectedFontSize)
        });
        
        previewContent.text(postText);
    }
}

// Update textarea styling
function updateTextareaStyling() {
    const textarea = $('#postInput');
    
    if (textarea.length > 0) {
        textarea.css({
            'background-color': selectedBackgroundColor,
            'color': selectedTextColor,
            'font-size': getFontSize(selectedFontSize)
        });
    }
}

// Get font size value
function getFontSize(size) {
    switch(size) {
        case 'large': return '20px';
        case 'extra-large': return '24px';
        default: return '16px';
    }
}

// Close colored post section
$(document).on("click", "#closeColorPost", function () {
    $('#colorPostSection').slideUp(300);
    resetColoredPost();
    
    // Hide posting detail if no other sections are open
    if (!$('#feelingSection').is(':visible') && !$('#pollSection').is(':visible') && !$('#locationSection').is(':visible') && !$('#gifSection').is(':visible')) {
        $('.posting-detail').slideUp(300);
    }
});

// Close GIF section
$(document).on("click", "#closeGif", function () {
    $('#gifSection').slideUp(300);
    resetGifForm();
    
    // Hide posting detail if no other sections are open
    if (!$('#feelingSection').is(':visible') && !$('#pollSection').is(':visible') && !$('#locationSection').is(':visible') && !$('#colorPostSection').is(':visible') && !$('#voiceNoteSection').is(':visible')) {
        $('.posting-detail').slideUp(300);
    }
});

// Close Voice Note section
$(document).on("click", "#closeVoiceNote", function () {
    $('#voiceNoteSection').slideUp(300);
    resetVoiceNoteForm();
    
    // Hide posting detail if no other sections are open
    if (!$('#feelingSection').is(':visible') && !$('#pollSection').is(':visible') && !$('#locationSection').is(':visible') && !$('#colorPostSection').is(':visible') && !$('#gifSection').is(':visible') && !$('#fileUploadSection').is(':visible')) {
        $('.posting-detail').slideUp(300);
    }
});

// Close File Upload section
$(document).on("click", "#closeFileUpload", function () {
    $('#fileUploadSection').slideUp(300);
    resetFileUploadForm();
    
    // Hide posting detail if no other sections are open
    if (!$('#feelingSection').is(':visible') && !$('#pollSection').is(':visible') && !$('#locationSection').is(':visible') && !$('#colorPostSection').is(':visible') && !$('#gifSection').is(':visible') && !$('#voiceNoteSection').is(':visible') && !$('#tagPeopleSection').is(':visible')) {
        $('.posting-detail').slideUp(300);
    }
});

// Close Tag People section
$(document).on("click", "#closeTagPeople", function () {
    $('#tagPeopleSection').slideUp(300);
    resetTagPeopleForm();
    
    // Hide posting detail if no other sections are open
    if (!$('#feelingSection').is(':visible') && !$('#pollSection').is(':visible') && !$('#locationSection').is(':visible') && !$('#colorPostSection').is(':visible') && !$('#gifSection').is(':visible') && !$('#voiceNoteSection').is(':visible') && !$('#fileUploadSection').is(':visible')) {
        $('.posting-detail').slideUp(300);
    }
});

// Reset colored post
function resetColoredPost() {
    // Remove colored post class
    $('#postInput').removeClass('colored-post');
    
    // Reset textarea styling
    $('#postInput').css({
        'background-color': '',
        'color': '',
        'font-size': ''
    });
    
    // Reset variables
    selectedBackgroundColor = '#ffffff';
    selectedTextColor = '#000000';
    selectedFontSize = 'normal';
    
    // Reset UI
    $('#backgroundColors .color-option').removeClass('selected');
    $('#textColors .color-option').removeClass('selected');
    $('.font-size-btn').removeClass('active');
    $('.font-size-btn[data-size="normal"]').addClass('active');
    
    // Reset preview
    updateColoredPostPreview();
}

// Update preview when textarea content changes
$('#postInput').on('input', function() {
    if ($('#colorPostSection').is(':visible')) {
        updateColoredPostPreview();
    }
});

// Escape HTML to avoid layout injection when rendering colored posts
function escapeHtml(str) {
    if (!str) return '';
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

// Handle feeling selection
$(document).on("click", ".feeling-type", function () {
    var selectedFeeling = $(this).data("feeling");
    $("#feeling-category").val(selectedFeeling);
    $(".selected-feeling-type").text(selectedFeeling).addClass("bg-info p-2 text-white mr-1");
    $("#feelingList").hide();
    var feelingSubType = `<ul class="list-group">`;
    var feelingFoot = `</ul>`;
    var feelingSubTypeHtml = "";
    
    if (selectedFeeling === "Feeling") {
        const feelings = [
            "Happy", "Loved", "Sad", "Very sad", "Angry", 
            "Confused", "Hot", "Broken", "expressionless", 
            "Cool", "Funny", "Tired", "Lovely", "Blessed", 
            "Shocked", "Sleepy", "Pretty", "Bored"
        ];
        
        feelingSubTypeHtml = feelings.map(feeling => 
            `<li class="list-group-item feeling-sub-type-item" data-feeling="${feeling}">${feeling}</li>`
        ).join('');
        $('.feeling-type-text').text("How are you feeling?");
        $('.feeling-input').remove();
    } else if (selectedFeeling === "Traveling") {
        $('.feeling-input').remove();
        $('.feeling-list').next().after('<input type="text" class="form-control mb-2 feeling-input" placeholder="Where are you traveling?">');
        $('.feeling-type-text').text("Where are you traveling?");
    } else if (selectedFeeling === "Watching") {
        $('.feeling-input').remove();
        $('.feeling-list').next().after('<input type="text" class="form-control mb-2 feeling-input" placeholder="Where are you watching?">');
        $('.feeling-type-text').text("Where are you watching?");
    } else if (selectedFeeling === "Listening") {
        $('.feeling-input').remove();
        $('.feeling-list').next().after('<input type="text" class="form-control mb-2 feeling-input" placeholder="What are you listening to?">');
        $('.feeling-type-text').text("What are you listening to?");
    }

    $(".feeling-sub-type").html(feelingSubType + feelingSubTypeHtml + feelingFoot).addClass("showing").removeClass("d-none");
});

$(document).on("keyup", ".feeling-input", function() {
    $("#feeling-description").val($(this).val());
});

$(".feeling-sub-type").on("click", ".feeling-sub-type-item", function() {
    var selectedFeeling = $(this).data("feeling");
    $("#feeling-description").val(selectedFeeling);
    $(".feeling-sub-type").removeClass("showing").addClass("d-none");
    $('.feeling-type-text').text(selectedFeeling);
});


// Advanced Poll Creation
let pollOptionCount = 2;

// Handle poll creation button
$(document).on("click", "#createPoll", function () {
    // Show posting detail section
    $('.posting-detail').slideDown(300);
    
    // Show poll section
    $('#pollSection').slideDown(300);
    resetPollForm();
    
    // Hide other sections
    $('#feelingSection').slideUp(300);
    $('#locationSection').slideUp(300);
});

// Close poll section
$(document).on("click", "#closePoll", function () {
    $('#pollSection').slideUp(300);
    resetPollForm();
    
    // Hide posting detail if no other sections are open
    if (!$('#feelingSection').is(':visible') && !$('#locationSection').is(':visible')) {
        $('.posting-detail').slideUp(300);
    }
});

// Add poll option
$(document).on("click", "#addPollOption", function () {
    if (pollOptionCount < 6) { // Maximum 6 options
        pollOptionCount++;
        const newOption = `
            <div class="poll-option-item mb-2">
                <div class="input-group">
                    <span class="input-group-text">${pollOptionCount}</span>
                    <input type="text" class="form-control poll-option-input" placeholder="Option ${pollOptionCount}" required>
                    <button class="btn btn-outline-danger remove-poll-option" type="button">
                        <i class="bi bi-x"></i>
                    </button>
                </div>
            </div>
        `;
        $('#pollOptionsList').append(newOption);
        
        // Disable add button if max reached
        if (pollOptionCount >= 6) {
            $('#addPollOption').prop('disabled', true).addClass('disabled');
        }
    }
});

// Remove poll option
$(document).on("click", ".remove-poll-option", function () {
    if (pollOptionCount > 2) { // Minimum 2 options
        $(this).closest('.poll-option-item').remove();
        pollOptionCount--;
        
        // Re-enable add button
        $('#addPollOption').prop('disabled', false).removeClass('disabled');
        
        // Renumber options
        $('.poll-option-item').each(function(index) {
            $(this).find('.input-group-text').text(index + 1);
            $(this).find('.poll-option-input').attr('placeholder', `Option ${index + 1}`);
        });
    }
});

// Validate poll form
function validatePollForm() {
    const question = $('#pollQuestion').val().trim();
    const options = [];
    
    $('.poll-option-input').each(function() {
        const option = $(this).val().trim();
        if (option) {
            options.push(option);
        }
    });
    
    if (!question) {
        myAlert.fire({
            icon: 'warning',
            title: 'Poll Question Required',
            text: 'Please enter a poll question.'
        });
        return false;
    }
    
    if (options.length < 2) {
        myAlert.fire({
            icon: 'warning',
            title: 'Poll Options Required',
            text: 'Please enter at least 2 poll options.'
        });
        return false;
    }
    
    return { question, options };
}

function resetPollForm() {
    $('#pollQuestion').val('');
    $('.poll-option-input').val('');
    pollOptionCount = 2;
    $('#addPollOption').prop('disabled', false).removeClass('disabled');
    
    // Reset to 2 options
    $('#pollOptionsList').html(`
        <div class="poll-option-item mb-2">
            <div class="input-group">
                <span class="input-group-text">1</span>
                <input type="text" class="form-control poll-option-input" placeholder="Option 1" required>
                <button class="btn btn-outline-danger remove-poll-option" type="button">
                    <i class="bi bi-x"></i>
                </button>
            </div>
        </div>
        <div class="poll-option-item mb-2">
            <div class="input-group">
                <span class="input-group-text">2</span>
                <input type="text" class="form-control poll-option-input" placeholder="Option 2" required>
                <button class="btn btn-outline-danger remove-poll-option" type="button">
                    <i class="bi bi-x"></i>
                </button>
            </div>
        </div>
    `);
}

// Handle event creation
$(document).on("click", "#createEvent", function () {
    // Redirect to event creation page or show event creation modal
    window.location.href = base_url + "/events/create";
});

// Advanced Location Check-in System
let selectedLocation = null;
let locationSearchTimeout = null;

// Handle location check-in button
$(document).on("click", "#checkIn", function () {
    // Show posting detail section
    $('.posting-detail').slideDown(300);
    
    // Show location section
    $('#locationSection').slideDown(300);
    resetLocationForm();
    
    // Hide other sections
    $('#feelingSection').slideUp(300);
    $('#pollSection').slideUp(300);
});

// Close location section
$(document).on("click", "#closeLocation", function () {
    $('#locationSection').slideUp(300);
    resetLocationForm();
    
    // Hide posting detail if no other sections are open
    if (!$('#feelingSection').is(':visible') && !$('#pollSection').is(':visible')) {
        $('.posting-detail').slideUp(300);
    }
});

// Location search functionality
$("#locationSearch").on("input", function () {
    const searchTerm = $(this).val().trim();
    
    // Clear previous timeout
    if (locationSearchTimeout) {
        clearTimeout(locationSearchTimeout);
    }
    
    // Hide results if search is empty
    if (!searchTerm) {
        $('#locationResults').hide();
        $('#noLocationResults').hide();
        return;
    }
    
    // Set timeout to avoid too many API calls
    locationSearchTimeout = setTimeout(() => {
        searchLocations(searchTerm);
    }, 500);
});

// Search locations using Google Places API
function searchLocations(searchTerm) {
    // Show loading state
    $('#locationResultsList').html('<div class="text-center py-3"><div class="spinner-border spinner-border-sm" role="status"></div><span class="ms-2">Searching...</span></div>');
    $('#locationResults').show();
    $('#noLocationResults').hide();
    
    // For demo purposes, we'll use a mock API response
    // In production, you would use Google Places API or similar
    setTimeout(() => {
        const mockResults = generateMockLocationResults(searchTerm);
        
        if (mockResults.length > 0) {
            displayLocationResults(mockResults);
        } else {
            showNoLocationResults();
        }
    }, 1000);
}

// Generate mock location results (replace with real API call)
function generateMockLocationResults(searchTerm) {
    const mockPlaces = [
        { id: 1, name: 'Starbucks Coffee', address: '123 Main St, Downtown', type: 'Coffee Shop', rating: 4.5 },
        { id: 2, name: 'Central Park', address: '456 Park Ave, City Center', type: 'Park', rating: 4.8 },
        { id: 3, name: 'Shopping Mall', address: '789 Commerce Blvd', type: 'Shopping Center', rating: 4.2 },
        { id: 4, name: 'Restaurant XYZ', address: '321 Food St, Downtown', type: 'Restaurant', rating: 4.6 },
        { id: 5, name: 'Gym & Fitness', address: '654 Health Ave', type: 'Gym', rating: 4.4 },
        { id: 6, name: 'Library', address: '987 Knowledge St', type: 'Library', rating: 4.7 },
        { id: 7, name: 'Movie Theater', address: '147 Entertainment Blvd', type: 'Entertainment', rating: 4.3 },
        { id: 8, name: 'Hospital', address: '258 Medical Center Dr', type: 'Hospital', rating: 4.9 }
    ];
    
    return mockPlaces.filter(place => 
        place.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        place.address.toLowerCase().includes(searchTerm.toLowerCase()) ||
        place.type.toLowerCase().includes(searchTerm.toLowerCase())
    );
}

// Display location search results
function displayLocationResults(results) {
    let resultsHtml = '';
    
    results.forEach(place => {
        resultsHtml += `
            <div class="location-result-item" data-location='${JSON.stringify(place)}'>
                <div class="location-result-content">
                    <div class="location-result-icon">
                        <i class="bi bi-geo-alt-fill text-primary"></i>
                    </div>
                    <div class="location-result-details">
                        <div class="location-result-name">${place.name}</div>
                        <div class="location-result-address">${place.address}</div>
                        <div class="location-result-type">${place.type}</div>
                    </div>
                    <div class="location-result-rating">
                        <i class="bi bi-star-fill text-warning"></i>
                        <span>${place.rating}</span>
                    </div>
                </div>
            </div>
        `;
    });
    
    $('#locationResultsList').html(resultsHtml);
    $('#locationResults').show();
    $('#noLocationResults').hide();
}

// Show no results message
function showNoLocationResults() {
    $('#locationResults').hide();
    $('#noLocationResults').show();
}

// Handle location result selection
$(document).on("click", ".location-result-item", function () {
    const locationData = $(this).data('location');
    selectLocation(locationData);
});

// Select a location
function selectLocation(locationData) {
    selectedLocation = locationData;
    
    // Hide search results
    $('#locationResults').hide();
    $('#noLocationResults').hide();
    
    // Show selected location preview
    $('#selectedLocationContent').html(`
        <div class="selected-location-item">
            <div class="selected-location-icon">
                <i class="bi bi-geo-alt-fill text-primary"></i>
            </div>
            <div class="selected-location-details">
                <div class="selected-location-name">${locationData.name}</div>
                <div class="selected-location-address">${locationData.address}</div>
                <div class="selected-location-type">${locationData.type}</div>
            </div>
        </div>
    `);
    
    $('#selectedLocationPreview').show();
    
    // Update form data
    $('#post-location').val(locationData.name);
    userLocation = locationData.address;
    
    // Show location badge in post area
    showLocationBadge(locationData.name, locationData.address);
}

// Use current location
$(document).on("click", "#useCurrentLocation", function () {
    if (navigator.geolocation) {
        $(this).prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Getting location...');
        
        navigator.geolocation.getCurrentPosition(function (position) {
            const currentLocation = {
                id: 'current',
                name: 'Current Location',
                address: `${position.coords.latitude.toFixed(6)}, ${position.coords.longitude.toFixed(6)}`,
                type: 'Current Location',
                rating: null,
                coordinates: {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                }
            };
            
            selectLocation(currentLocation);
            $("#useCurrentLocation").prop('disabled', false).html('<i class="bi bi-geo-alt-fill"></i><span class="d-none d-sm-inline">Current</span>');
        }, function (error) {
            myAlert.fire({
                icon: 'error',
                title: 'Location Error',
                text: 'Unable to get your current location. Please try searching for a place instead.'
            });
            $("#useCurrentLocation").prop('disabled', false).html('<i class="bi bi-geo-alt-fill"></i><span class="d-none d-sm-inline">Current</span>');
        });
    } else {
        myAlert.fire({
            icon: 'error',
            title: 'Not Supported',
            text: 'Geolocation is not supported by this browser.'
        });
    }
});

// Clear location search
$(document).on("click", "#clearLocationSearch", function () {
    $('#locationSearch').val('');
    $('#locationResults').hide();
    $('#noLocationResults').hide();
});

// Remove selected location
$(document).on("click", "#removeSelectedLocation", function () {
    removeSelectedLocation();
});

// Add custom location
$(document).on("click", "#addCustomLocation", function () {
    $('#customLocationInput').show();
    $('#noLocationResults').hide();
});

// Save custom location
$(document).on("click", "#saveCustomLocation", function () {
    const customLocationText = $('#customLocationText').val().trim();
    
    if (customLocationText) {
        const customLocation = {
            id: 'custom',
            name: customLocationText,
            address: customLocationText,
            type: 'Custom Location',
            rating: null
        };
        
        selectLocation(customLocation);
        $('#customLocationInput').hide();
        $('#customLocationText').val('');
    } else {
        myAlert.fire({
            icon: 'warning',
            title: 'Location Required',
            text: 'Please enter a custom location name.'
        });
    }
});

// Cancel custom location
$(document).on("click", "#cancelCustomLocation", function () {
    $('#customLocationInput').hide();
    $('#customLocationText').val('');
    $('#noLocationResults').show();
});

// Show location badge in post area
function showLocationBadge(locationName, locationAddress) {
    const locationBadge = `
        <div class="selected-location-badge d-inline-flex align-items-center bg-light rounded-pill px-3 py-1 me-2 mb-2">
            <i class="bi bi-geo-alt-fill text-primary me-2"></i>
            <div class="location-badge-content">
                <div class="location-badge-name">${locationName}</div>
                <div class="location-badge-address small text-muted">${locationAddress}</div>
            </div>
            <button type="button" class="btn-close btn-close-sm ms-2" onclick="removeSelectedLocation()"></button>
        </div>
    `;
    
    // Remove existing location badge
    $('.selected-location-badge').remove();
    
    // Add new location badge after textarea
    $('#postInput').after(locationBadge);
}

// Remove selected location
function removeSelectedLocation() {
    selectedLocation = null;
    $('#post-location').val('');
    userLocation = '';
    $('.selected-location-badge').remove();
    $('#selectedLocationPreview').hide();
    $('#locationSection').slideUp(300);
    
    // Hide posting detail if no other sections are open
    if (!$('#feelingSection').is(':visible') && !$('#pollSection').is(':visible')) {
        $('.posting-detail').slideUp(300);
    }
}

// Reset location form
function resetLocationForm() {
    selectedLocation = null;
    $('#locationSearch').val('');
    $('#locationResults').hide();
    $('#noLocationResults').hide();
    $('#selectedLocationPreview').hide();
    $('#customLocationInput').hide();
    $('#customLocationText').val('');
    $('#post-location').val('');
    userLocation = '';
    $('.selected-location-badge').remove();
}

// Handle post submission
// Handle live video
$(document).on("click", "#liveVideo", function () {
    // Redirect to live video page or show live video modal
    window.location.href = base_url + "/live-video";
});

// Enhanced Post Validation Functions
function validatePostContent(postText, mediaFiles, pollData) {
    const errors = [];
    
    // Check if post has any content
    if (!postText && mediaFiles.length === 0 && !pollData) {
        errors.push('Please enter text, upload media, or create a poll.');
    }
    
    // Validate post text length
    if (postText && postText.length > 5000) {
        errors.push('Post text cannot exceed 5000 characters.');
    }
    
    // Validate media files
    if (mediaFiles.length > 0) {
        const validation = validateMediaFiles(mediaFiles);
        if (!validation.isValid) {
            errors.push(...validation.errors);
        }
    }
    
    // Validate poll data
    if (pollData) {
        const pollValidation = validatePollData(pollData);
        if (!pollValidation.isValid) {
            errors.push(...pollValidation.errors);
        }
    }
    
    return {
        isValid: errors.length === 0,
        errors: errors
    };
}

function validateMediaFiles(files) {
    const errors = [];
    const maxFileSize = 50 * 1024 * 1024; // 50MB
    const allowedImageTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    const allowedVideoTypes = ['video/mp4', 'video/avi', 'video/mov', 'video/wmv', 'video/flv'];
    const allowedAudioTypes = ['audio/mp3', 'audio/mpeg', 'audio/wav', 'audio/ogg', 'audio/m4a', 'audio/aac', 'audio/flac', 'audio/webm'];
    const allowedDocTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain', 'application/rtf', 'application/vnd.oasis.opendocument.text'];
    const allowedArchiveTypes = ['application/zip', 'application/x-rar-compressed', 'application/x-7z-compressed', 'application/x-tar', 'application/gzip'];
    
    let imageCount = 0;
    let videoCount = 0;
    let audioCount = 0;
    
    files.forEach((file, index) => {
        // Check file size
        if (file.size > maxFileSize) {
            errors.push(`File "${file.name}" is too large. Maximum size is 50MB.`);
        }
        
        // Check file type and count
        if (file.type.startsWith('image/')) {
            if (!allowedImageTypes.includes(file.type)) {
                errors.push(`Image file "${file.name}" has an unsupported format.`);
            }
            imageCount++;
            if (imageCount > 10) {
                errors.push('Maximum 10 images allowed per post.');
            }
        } else if (file.type.startsWith('video/')) {
            if (!allowedVideoTypes.includes(file.type)) {
                errors.push(`Video file "${file.name}" has an unsupported format.`);
            }
            videoCount++;
            if (videoCount > 1) {
                errors.push('Maximum 1 video allowed per post.');
            }
        } else if (file.type.startsWith('audio/')) {
            if (!allowedAudioTypes.includes(file.type)) {
                errors.push(`Audio file "${file.name}" has an unsupported format.`);
            }
            audioCount++;
            if (audioCount > 1) {
                errors.push('Maximum 1 audio file allowed per post.');
            }
        } else {
            if (![...allowedDocTypes, ...allowedArchiveTypes].includes(file.type)) {
                errors.push(`File "${file.name}" has an unsupported type (${file.type}).`);
            }
        }
    });
    
    return {
        isValid: errors.length === 0,
        errors: errors
    };
}

function validatePollData(pollData) {
    const errors = [];
    
    if (!pollData.question || pollData.question.trim().length === 0) {
        errors.push('Poll question is required.');
    } else if (pollData.question.length > 200) {
        errors.push('Poll question cannot exceed 200 characters.');
    }
    
    if (!pollData.options || pollData.options.length < 2) {
        errors.push('Poll must have at least 2 options.');
    } else if (pollData.options.length > 6) {
        errors.push('Poll cannot have more than 6 options.');
    } else {
        pollData.options.forEach((option, index) => {
            if (!option || option.trim().length === 0) {
                errors.push(`Poll option ${index + 1} cannot be empty.`);
            } else if (option.length > 100) {
                errors.push(`Poll option ${index + 1} cannot exceed 100 characters.`);
            }
        });
    }
    
    return {
        isValid: errors.length === 0,
        errors: errors
    };
}

function validatePostOptions() {
    const errors = [];
    
    // Validate schedule datetime
    if (isScheduled) {
        if (!scheduledDateTime) {
            errors.push('Please select a date and time for your scheduled post.');
        } else {
            const selectedDate = new Date(scheduledDateTime);
            const now = new Date();
            if (selectedDate <= now) {
                errors.push('Scheduled post time must be in the future.');
            }
        }
    }
    
    // Validate anonymous post
    if (isAnonymous && !confirm('Are you sure you want to post anonymously?')) {
        errors.push('Anonymous posting was cancelled.');
    }
    
    return {
        isValid: errors.length === 0,
        errors: errors
    };
}

function validateLocationData() {
    const errors = [];
    
    if (selectedLocation) {
        if (!selectedLocation.name || selectedLocation.name.trim().length === 0) {
            errors.push('Location name is required.');
        }
        if (selectedLocation.name.length > 100) {
            errors.push('Location name cannot exceed 100 characters.');
        }
    }
    
    return {
        isValid: errors.length === 0,
        errors: errors
    };
}

function validateFeelingData() {
    const errors = [];
    
    const feelingCategory = $("#feeling-category").val();
    const feelingDescription = $("#feeling-description").val();
    
    if (feelingCategory && !feelingDescription) {
        errors.push('Please select a feeling description.');
    }
    if (!feelingCategory && feelingDescription) {
        errors.push('Please select a feeling category.');
    }
    
    return {
        isValid: errors.length === 0,
        errors: errors
    };
}

function validateTaggedPeople() {
    const errors = [];
    
    if (taggedPeople.length > 20) {
        errors.push('Maximum 20 people can be tagged in a post.');
    }
    
    return {
        isValid: errors.length === 0,
        errors: errors
    };
}

// Enhanced Post Submission Function
function submitPost(formData) {
    return new Promise((resolve, reject) => {
        // Show loading state
        $("#postButton").prop("disabled", true).html('<span class="spinner-border spinner-border-sm me-2"></span>Posting...');
        
        // Add CSRF token
        const token = $('meta[name="csrf-token"]').attr('content');
        if (token) {
            formData.append('_token', token);
        }
        
        axios.post(base_url + "/webapi/post/create", formData, {
            headers: { 
                "Content-Type": "multipart/form-data",
                "X-Requested-With": "XMLHttpRequest"
            },
            timeout: 60000, // 60 seconds timeout
            onUploadProgress: (progressEvent) => {
                const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                $("#postButton").html(`<span class="spinner-border spinner-border-sm me-2"></span>Uploading... ${percentCompleted}%`);
            }
        })
        .then(response => {
            if (response.data.status === 200) {
                resolve(response.data);
            } else {
                reject(new Error(response.data.message || 'Failed to create post.'));
            }
        })
        .catch(error => {
            
            
            let errorMessage = 'Failed to create post. Please try again.';
            
            if (error.response) {
                // Server responded with error
                const status = error.response.status;
                const data = error.response.data;
                
                switch (status) {
                    case 422:
                        errorMessage = data.message || 'Validation failed. Please check your input.';
                        break;
                    case 413:
                        errorMessage = 'File size too large. Please reduce file size and try again.';
                        break;
                    case 429:
                        errorMessage = 'Too many requests. Please wait a moment and try again.';
                        break;
                    case 500:
                        errorMessage = 'Server error. Please try again later.';
                        break;
                    default:
                        errorMessage = data.message || `Error ${status}: Failed to create post.`;
                }
            } else if (error.request) {
                // Network error
                errorMessage = 'Network error. Please check your connection and try again.';
            } else if (error.code === 'ECONNABORTED') {
                // Timeout error
                errorMessage = 'Request timed out. Please try again.';
            }
            
            reject(new Error(errorMessage));
        });
    });
}

// Handle post submission
$(document).on("click", "#postButton", function () {
    // Prevent double submission
    if ($(this).prop('disabled')) {
        return;
    }
    
    let postText = $("#postInput").val().trim();
    
    // Check if poll is active
    let pollData = null;
    if ($('#pollSection').is(':visible')) {
        const pollValidation = validatePollForm();
        if (pollValidation) {
            pollData = pollValidation;
        } else {
            return; // Validation failed
        }
    }
    
    // Comprehensive validation
    const contentValidation = validatePostContent(postText, mediaFiles, pollData);
    const optionsValidation = validatePostOptions();
    const locationValidation = validateLocationData();
    const feelingValidation = validateFeelingData();
    const taggedValidation = validateTaggedPeople();
    
    const allErrors = [
        ...contentValidation.errors,
        ...optionsValidation.errors,
        ...locationValidation.errors,
        ...feelingValidation.errors,
        ...taggedValidation.errors
    ];
    
    if (allErrors.length > 0) {
        const errorMessage = allErrors.length === 1 ? allErrors[0] : 
            'Please fix the following errors:\n• ' + allErrors.join('\n• ');
        
        myAlert.fire({
            icon: 'error',
            title: 'Validation Error',
            text: errorMessage,
            confirmButtonText: 'OK'
        });
        return;
    }
    
    // Get post type from hidden input
    let postType = $("#postType").val();
    
    let formData = new FormData();
    formData.append("post_text", postText);
    formData.append("privacy_level", selectedPrivacy);
    formData.append("privacy", selectedPrivacy);
    
    if(pollData) {
        formData.append("post_type", 'poll');
        formData.append("poll_question", pollData.question);
        formData.append("poll_options", JSON.stringify(pollData.options));
        formData.append("allow_multiple_votes", $('#allowMultipleVotes').is(':checked') ? '1' : '0');
        formData.append("hide_results", $('#hideResults').is(':checked') ? '1' : '0');
    } else {
        formData.append("post_type", postType);
    }
    
    // Add feeling data
    const feelingCategory = $("#feeling-category").val();
    const feelingDescription = $("#feeling-description").val();
    
    if (feelingCategory && feelingDescription) {
        formData.append("feeling_category", feelingCategory);
        formData.append("feeling_description", feelingDescription);
    }
    
    // Add location data
    if (selectedLocation) {
        formData.append("location", selectedLocation.address);
        formData.append("post_location", selectedLocation.name);
        formData.append("location_type", selectedLocation.type);
        if (selectedLocation.coordinates) {
            formData.append("location_lat", selectedLocation.coordinates.lat);
            formData.append("location_lng", selectedLocation.coordinates.lng);
        }
    }
    
    // Add colored post data
    if ($('#colorPostSection').is(':visible')) {
        formData.append("is_colored_post", '1');
        formData.append("background_color", selectedBackgroundColor);
        formData.append("text_color", selectedTextColor);
        formData.append("font_size", selectedFontSize);
    }
    
    // Add GIF data
    if (selectedGif) {
        formData.append("gif_id", selectedGif.id);
        formData.append("gif_url", String(selectedGif.url).replace(/^http:\/\//,'https://'));
        formData.append("gif_title", selectedGif.title || 'GIF');
    }
    
    // Add tagged people data
    if (taggedPeople.length > 0) {
        const taggedPeopleIds = taggedPeople.map(person => person.id);
        formData.append("tagged_people", JSON.stringify(taggedPeopleIds));
        formData.append("tagged_people_names", JSON.stringify(taggedPeople.map(person => person.name)));
    }
    
    // Add post options data
    formData.append("is_scheduled", isScheduled ? '1' : '0');
    formData.append("is_anonymous", isAnonymous ? '1' : '0');
    formData.append("tips_enabled", isTipsEnabled ? '1' : '0');
    
    if (isScheduled && scheduledDateTime) {
        formData.append("scheduled_datetime", scheduledDateTime);
    }
    
    if (postType == 'group_post') {
        let groupId = $("#groupId").val() || $("#selectedGroupId").val();
        if (groupId) formData.append("group_id", groupId);
    }
    if (postType == 'page_post') {
        let pageId = $("#pageId").val() || $("#selectedPageId").val();
        if (pageId) formData.append("page_id", pageId);
    }
    
    let hasVideo = false;
    let hasAudio = false;
    let imageIndex = 0;

    $.each(mediaFiles, function (_, file) {
        if (file.type.startsWith("video") && !hasVideo) {
            formData.append("video", file);
            hasVideo = true;
        } else if (file.type.startsWith("audio") && !hasAudio) {
            formData.append("audio", file);
            hasAudio = true;
        } else if (file.type.startsWith("image")) {
            formData.append(`images[${imageIndex}]`, file);
            imageIndex++;
        } else {
            // Generic files go as attachments[]
            formData.append('attachments[]', file);
        }
    });

    // Submit post using enhanced submission function
    submitPost(formData)
        .then(response => {
            // Success - reset form
            $("#postInput").val("");
            mediaFiles = [];
            updateMediaPreview();
            
            // Reset feeling selection
            resetFeelingSelection();
            
            // Reset poll
            $('#pollSection').slideUp(300);
            resetPollForm();
            
            // Reset location
            $('#preview-area').addClass("d-none").empty();
            resetLocationForm();
            
            // Reset colored post
            $('#colorPostSection').slideUp(300);
            resetColoredPost();
            
            // Reset GIF
            $('#gifSection').slideUp(300);
            resetGifForm();
            
            // Reset Voice Note
            $('#voiceNoteSection').slideUp(300);
            resetVoiceNoteForm();
            
            // Reset File Upload
            $('#fileUploadSection').slideUp(300);
            resetFileUploadForm();
            
            // Reset Tag People
            $('#tagPeopleSection').slideUp(300);
            resetTagPeopleForm();
            
            // Reset Post Options
            resetPostOptions();
            
            // Reset AI Features
            initAIFeatures();
            
            // Hide posting details
            $('.posting-detail').slideUp(300);
            
            // Clear preserved state on success
            preservedFormState = null;
            
            // Remove highlight and blur overlay
            removeHighlightPost();
            
            // Remove active-input class from post input
            $("#postInput").removeClass("active-input");
            
            // Show success message
            myAlert.fire({
                icon: 'success',
                title: 'Success!',
                text: 'Your post has been created successfully.',
                timer: 3000,
                timerProgressBar: true
            });
            
            // Refresh feed
            loadNewsFeed(response.data.id);
        })
        .catch(error => {
            // Don't reset the form on error - preserve user input
            $("#postButton").prop("disabled", false).text("Post");
            
            handlePostError(error, 'post_submission');
            
            // Show retry option for certain errors
            if (error.message.includes('Network error') || error.message.includes('timeout') || error.message.includes('Server error')) {
                myAlert.fire({
                    icon: 'error',
                    title: 'Post Failed',
                    text: error.message,
                    showCancelButton: true,
                    confirmButtonText: 'Retry',
                    cancelButtonText: 'Cancel',
                    reverseButtons: true
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Trigger retry
                        $('#retryPost').click();
                    }
                });
            }
        })
        .finally(() => {
            $("#postButton").prop("disabled", false).text("Post");
        });
});

    
    // Post comment button clicks
    $(document).on('click', '.post-comment-btn', function() {
        const postId = $(this).data('post-id');
        const commentText = $(`.comment-input[data-post-id="${postId}"]`).val();
        if (commentText.trim()) {
            postComment(postId, commentText);
        }
    });
    
    // Comment input enter key press
    $(document).on('keydown', '.comment-input', function(e) {
        if (e.keyCode === 13 && !e.shiftKey) { // Enter without shift
            e.preventDefault();
            const postId = $(this).data('post-id');
            const commentText = $(this).val();
            if (commentText.trim()) {
                postComment(postId, commentText);
            }
        }
    });
    
   
    // Load more comments click
    
// Update the load more comments event handler
$(document).on('click', '.load-more-comments', function() {
    const postId = $(this).data('post-id');
    const offset = $(this).data('offset');
    
    $(this).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading...');
    
    axios.post(base_url + "/webapi/post/comment-action", {
        post_id: postId,
        offset: offset,
        action: 'get',
        limit: 10
    })
    .then(response => {
        if (response.data.status === 200) {
            const comments = response.data.data;
            
            if (comments.length > 0) {
                let commentsHtml = '';
                
                comments.forEach(comment => {
                    commentsHtml += renderComment(comment, postId);
                });
                
                // Insert new comments before the load more button
                $(this).before(commentsHtml);
                
                // Update the load more button
                $(this).data('offset', offset + comments.length);
                $(this).html('<i class="bi bi-chat-text me-1"></i> Load more comments');
            } else {
                // No more comments
                $(this).html('No more comments').prop('disabled', true);
            }
        } else {
            $(this).html('Error loading comments').prop('disabled', true);
        }
    })
    .catch(error => {
        console.error("Error:", error);
        $(this).html('Error loading comments').prop('disabled', true);
    });
});
    
    // Post action event handlers
    $(document).on('click', '.save-post-btn', function() {
        const postId = $(this).data('post-id');
        savePost(postId);
    });
    
    $(document).on('click', '.edit-post-btn', function() {
        const postId = $(this).data('post-id');
        openEditPostModal(postId);
    });
    
    $(document).on('click', '.delete-post-btn', function() {
        const postId = $(this).data('post-id');
        deletePost(postId);
    });
    
    $(document).on('click', '.toggle-comments-btn', function() {
        const postId = $(this).data('post-id');
        toggleComments(postId);
    });
    
    $(document).on('click', '.report-post-btn', function() {
        const postId = $(this).data('post-id');
        reportPost(postId);
    });
    
    $(document).on('click', '.hide-post-btn', function() {
        const postId = $(this).data('post-id');
        $(`#post-${postId}`).fadeOut(300, function() {
            $(this).remove();
        });
        showAlert('success', 'Post hidden', 'You won\'t see this post in your feed anymore');
    });
    
    $(document).on('click', '.follow-user-btn', function() {
        const userId = $(this).data('user-id');
        // Would normally call API to follow/unfollow user
        $(this).html('<i class="bi bi-person-check pe-2"></i> Following');
        showAlert('success', 'Success', 'You are now following this user');
    });
    
    $(document).on('click', '.share-dm-btn', function() {
        const postId = $(this).data('post-id');
        // Modal to select user for DM
        shareWithUser(postId);
    });
    
    $(document).on('click', '.copy-link-btn', function() {
        const postId = $(this).data('post-id');
        copyPostLink(postId);
    });
    
    $(document).on('click', '.share-now-btn', function() {
        const postId = $(this).data('post-id');
        sharePost(postId, 'now');
    });
    
    $(document).on('click', '.share-with-text-btn', function() {
        const postId = $(this).data('post-id');
        shareWithText(postId);
    });

    // Handle post input focus to show posting details
$(document).on("click", "#postInput", function() {
    $(".posting-detail").slideDown(300);
    $(this).addClass("active-input");
    highlightPost();
    
    // Check if there's a preserved draft and offer to restore it
    if (preservedFormState && !$("#postInput").val().trim()) {
        myAlert.fire({
            icon: 'question',
            title: 'Draft Available',
            text: 'You have a saved draft from a previous attempt. Would you like to restore it?',
            showCancelButton: true,
            confirmButtonText: 'Restore Draft',
            cancelButtonText: 'Start Fresh',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                restoreFormState();
            }
        });
    }
    
    // Add a click handler to the document to detect clicks outside
    $(document).on("click.postInput", function(event) {
        // If the click is outside the post card and the input is empty, hide the details
        if (!$(event.target).closest(".post-creation-card").length && $("#postInput").val().trim() === "") {
            $(".posting-detail").slideUp(300);
            $("#postInput").removeClass("active-input");
            
            $(document).off("click.postInput");
        }
    });
    
    // Add keyboard shortcut for saving draft (Ctrl+S or Cmd+S)
    $(document).on("keydown", "#postInput", function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            saveDraft();
        }
    });
});

// GIF Search and Interaction Handlers
$(document).on("click", "#searchGif", function() {
    const searchTerm = $('#gifSearch').val().trim();
    if (searchTerm) {
        currentGifSearchTerm = searchTerm;
        $('#gifResults').show();
        $('#trendingGifs').hide();
        searchGifs(searchTerm);
    }
});

$(document).on("keypress", "#gifSearch", function(e) {
    if (e.keyCode === 13) { // Enter key
        const searchTerm = $(this).val().trim();
        if (searchTerm) {
            currentGifSearchTerm = searchTerm;
            $('#gifResults').show();
            $('#trendingGifs').hide();
            searchGifs(searchTerm);
        }
    }
});

$(document).on("click", "#clearGifSearch", function() {
    $('#gifSearch').val('');
    $('#gifResults').hide();
    $('#trendingGifs').show();
    currentGifSearchTerm = '';
    gifSearchOffset = 0;
});

$(document).on("click", "#loadMoreGifs", function() {
    if (currentGifSearchTerm) {
        gifSearchOffset += 20;
        searchGifs(currentGifSearchTerm, gifSearchOffset, true);
    }
});

$(document).on("click", "#removeSelectedGif", function() {
    removeSelectedGif();
});

$(document).on("click", ".gif-item", function() {
    const gifData = JSON.parse($(this).data('gif'));
    selectGif(gifData);
});

// Voice Note Recording Event Handlers
$(document).on("click", "#startRecording", function() {
    startRecording();
});

$(document).on("click", "#stopRecording", function() {
    stopRecording();
});

$(document).on("click", "#pauseRecording", function() {
    pauseRecording();
});

$(document).on("click", "#resumeRecording", function() {
    resumeRecording();
});

$(document).on("click", "#saveRecording", function() {
    saveRecordedAudio();
});

$(document).on("click", "#deleteRecording", function() {
    deleteRecordedAudio();
});

// File Upload Event Handlers
$(document).on("click", "#browseFiles", function() {
    $('#fileInput').click();
});

// Allow clicking on the drop zone background to open the file picker
$(document).on('click', '#uploadZone', function(e) {
    if (e.target && e.target.id === 'uploadZone') {
        $('#fileInput').click();
    }
});

// Handle file input change for generic files
$(document).on('change', '#fileInput', function(e) {
    const files = e.target.files;
    if (files && files.length > 0) {
        addFiles(files);
    }
});

$(document).on("change", "#fileInput", function(e) {
    addFiles(e.target.files);
    // Reset input to allow selecting the same file again
    $(this).val('');
});

$(document).on("click", ".filter-btn", function() {
    currentFileFilter = $(this).data('filter');
    updateFilterButtons();
    updateFileList();
});

$(document).on("click", ".remove-file", function() {
    const index = $(this).data('index');
    removeFile(index);
});

$(document).on("click", "#addFilesToPost", function() {
    addFilesToPost();
});

$(document).on("click", "#clearAllFiles", function() {
    clearAllFiles();
});

// Drag and Drop functionality
$(document).on("dragover", "#uploadZone", function(e) {
    e.preventDefault();
    $(this).addClass('dragover');
});

$(document).on("dragleave", "#uploadZone", function(e) {
    e.preventDefault();
    $(this).removeClass('dragover');
});

$(document).on("drop", "#uploadZone", function(e) {
    e.preventDefault();
    $(this).removeClass('dragover');
    
    const files = e.originalEvent.dataTransfer.files;
    addFiles(files);
});

// Click to upload
$(document).on("click", "#uploadZone", function() {
    $('#fileInput').click();
});

// Tag People Event Handlers
$(document).on("input", "#searchPeople", function() {
    const searchTerm = $(this).val().trim();
    
    // Clear previous timeout
    if (searchTimeout) {
        clearTimeout(searchTimeout);
    }
    
    if (searchTerm.length === 0) {
        $('#searchResults').hide();
        $('#peopleSuggestions').show();
        return;
    }
    
    // Set timeout for search
    searchTimeout = setTimeout(() => {
        $('#peopleSuggestions').hide();
        $('#searchResults').show();
        searchPeople(searchTerm);
    }, 500);
});

$(document).on("click", ".add-person-tag", function() {
    const personId = $(this).data('person-id');
    addPersonToTagged(personId);
});

$(document).on("click", ".remove-person-tag", function() {
    const personId = $(this).data('person-id');
    removePersonFromTagged(personId);
});

$(document).on("click", ".remove-tag", function() {
    const personId = $(this).data('person-id');
    removePersonFromTagged(personId);
});

$(document).on("click", "#saveTags", function() {
    saveTags();
});

$(document).on("click", "#clearAllTags", function() {
    clearAllTags();
});

// Post Options Event Handlers
$(document).on("change", "#is_schedule", function() {
    handleScheduleToggle();
});

$(document).on("change", "#is_anonymous", function() {
    handleAnonymousToggle();
});

$(document).on("change", "#tips_enabled", function() {
    handleTipsToggle();
});

$(document).on("change", ".js_publisher-schedule-date", function() {
    const selectedDateTime = $(this).val();
    if (selectedDateTime) {
        scheduledDateTime = selectedDateTime;
    }
});

// AI Features Event Handlers
$(document).on("click", "#generateAIPost", function() {
    $('#aiPostSection').slideDown(300);
    $('#aiImageSection').slideUp(300);
    hideAllOtherSections();
});

$(document).on("click", "#generateAIImage", function() {
    $('#aiImageSection').slideDown(300);
    $('#aiPostSection').slideUp(300);
    hideAllOtherSections();
});

$(document).on("click", "#closeAIPost", function() {
    $('#aiPostSection').slideUp(300);
    resetAIPostForm();
});

$(document).on("click", "#closeAIImage", function() {
    $('#aiImageSection').slideUp(300);
    resetAIImageForm();
});

$(document).on("click", "#generatePostBtn", function() {
    handleAIPostGeneration();
});

$(document).on("click", "#generateImageBtn", function() {
    handleAIImageGeneration();
});

$(document).on("click", "#useGeneratedPost", function() {
    useGeneratedPost();
});

$(document).on("click", "#useGeneratedImage", function() {
    useGeneratedImage();
});

$(document).on("click", "#regeneratePost", function() {
    handleAIPostGeneration();
});

$(document).on("click", "#regenerateImage", function() {
    handleAIImageGeneration();
});

$(document).on("click", "#downloadGeneratedImage", function() {
    downloadGeneratedImage();
});

$(document).on("click", "#clearAIPost", function() {
    resetAIPostForm();
});

$(document).on("click", "#clearAIImage", function() {
    resetAIImageForm();
});

// AI Style Button Handlers
$(document).on("click", ".ai-style-btn", function() {
    $('.ai-style-btn').removeClass('active');
    $(this).addClass('active');
    selectedPostStyle = $(this).data('style');
});

$(document).on("click", ".ai-image-style-btn", function() {
    $('.ai-image-style-btn').removeClass('active');
    $(this).addClass('active');
    selectedImageStyle = $(this).data('style');
});

$(document).on("click", ".ai-size-btn", function() {
    $('.ai-size-btn').removeClass('active');
    $(this).addClass('active');
    selectedImageSize = $(this).data('size');
});

// Enhanced Post Input Event Handlers
$(document).on("input", "#postInput", function() {
    validatePostInput();
});

$(document).on("keydown", "#postInput", function(e) {
    const charCount = $(this).val().length;
    const maxChars = 5000;
    
    // Prevent typing if character limit exceeded
    if (charCount >= maxChars && e.key.length === 1 && !e.ctrlKey && !e.metaKey) {
        e.preventDefault();
        myAlert.fire({
            icon: 'warning',
            title: 'Character Limit Reached',
            text: 'Post cannot exceed 5000 characters.',
            timer: 2000,
            timerProgressBar: true
        });
    }
});

// Enhanced Media Upload Validation
$(document).on("change", "#photoInput, #videoInput, #audioInput", function(e) {
    const files = e.target.files;
    if (files.length > 0) {
        const validation = validateMediaBeforeUpload(files);
        if (!validation.isValid) {
            const errorMessage = validation.errors.join('\n• ');
            myAlert.fire({
                icon: 'error',
                title: 'Upload Error',
                text: 'Please fix the following errors:\n• ' + errorMessage,
                confirmButtonText: 'OK'
            });
            
            // Clear the input
            $(this).val('');
            return;
        }
    }
});

// Enhanced Form Reset Handler
$(document).on("click", "#resetPostForm", function() {
    myAlert.fire({
        icon: 'warning',
        title: 'Reset Form',
        text: 'Are you sure you want to reset the entire post form? This will clear all content.',
        showCancelButton: true,
        confirmButtonText: 'Yes, Reset',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            resetPostForm();
        }
    });
});

// Enhanced Error Recovery
$(document).on("click", "#retryPost", function() {
    // Store current form data
    const currentData = {
        postText: $("#postInput").val(),
        mediaFiles: [...mediaFiles],
        pollData: $('#pollSection').is(':visible') ? validatePollForm() : null,
        feelingCategory: $("#feeling-category").val(),
        feelingDescription: $("#feeling-description").val(),
        selectedLocation: selectedLocation,
        selectedGif: selectedGif,
        taggedPeople: [...taggedPeople],
        isScheduled: isScheduled,
        scheduledDateTime: scheduledDateTime,
        isAnonymous: isAnonymous,
        isTipsEnabled: isTipsEnabled
    };
    
    // Reset form
    resetPostForm();
    
    // Restore data
    setTimeout(() => {
        $("#postInput").val(currentData.postText);
        mediaFiles = currentData.mediaFiles;
        updateMediaPreview();
        
        if (currentData.pollData) {
            $('#pollSection').slideDown(300);
            // Restore poll data
        }
        
        if (currentData.feelingCategory && currentData.feelingDescription) {
            $("#feeling-category").val(currentData.feelingCategory);
            $("#feeling-description").val(currentData.feelingDescription);
        }
        
        if (currentData.selectedLocation) {
            selectedLocation = currentData.selectedLocation;
            showLocationBadge(currentData.selectedLocation.name, currentData.selectedLocation.address);
        }
        
        if (currentData.selectedGif) {
            selectedGif = currentData.selectedGif;
            showGifBadge(currentData.selectedGif.title, currentData.selectedGif.url);
        }
        
        taggedPeople = currentData.taggedPeople;
        updateTaggedPeopleList();
        
        isScheduled = currentData.isScheduled;
        scheduledDateTime = currentData.scheduledDateTime;
        isAnonymous = currentData.isAnonymous;
        isTipsEnabled = currentData.isTipsEnabled;
        
        // Update UI
        $('#is_schedule').prop('checked', isScheduled);
        $('#is_anonymous').prop('checked', isAnonymous);
        $('#tips_enabled').prop('checked', isTipsEnabled);
        
        if (isScheduled && scheduledDateTime) {
            $('#schedule-datetime-wrapper').show();
            $('.js_publisher-schedule-date').val(scheduledDateTime);
        }
        
        myAlert.fire({
            icon: 'success',
            title: 'Form Restored',
            text: 'Your post data has been restored. You can now try posting again.',
            timer: 3000,
            timerProgressBar: true
        });
    }, 100);
});

// Prevent the document click handler from firing when clicking inside the card
$(document).on("click", ".post-creation-card", function(event) {
    event.stopPropagation();
});

// Remove highlight when clicking highlighter
$(document).on("click", ".post-highlighter", function() {
    removeHighlightPost();
});

// Highlight post function
function highlightPost() {
    $(".post-creation-card").addClass("post-active");
    $(".post-highlighter").show();
    $("html, body").animate({ scrollTop: $(".post-creation-card").offset().top - 20 }, "slow");
}

// Remove highlight function
function removeHighlightPost() {
    $(".post-creation-card").removeClass("post-active");
    $(".post-highlighter").hide();
}

// GIF Functionality Variables
let selectedGif = null;
let gifSearchOffset = 0;
let currentGifSearchTerm = '';

// Initialize GIF Section
function initGifSection() {
    // Load trending GIFs on initialization
    loadTrendingGifs();
    
    // Clear any previous search
    $('#gifSearch').val('');
    $('#gifResults').hide();
    $('#selectedGifPreview').hide();
    selectedGif = null;
    gifSearchOffset = 0;
    currentGifSearchTerm = '';
}

// Load trending GIFs
function loadTrendingGifs() {
    const trendingGrid = $('#trendingGifGrid');
    trendingGrid.html('<div class="gif-loading"><div class="spinner-border" role="status"></div><div class="mt-2">Loading trending GIFs...</div></div>');
    axios.get(base_url + '/webapi/gifs/trending', { params: { provider: 'giphy', limit: 18 } })
        .then(res => {
            if (res.data && res.data.status === 200) {
                displayGifs(res.data.data, trendingGrid);
            } else {
                trendingGrid.html('<div class="text-center text-muted py-4">Failed to load GIFs</div>');
            }
        })
        .catch(() => {
            trendingGrid.html('<div class="text-center text-muted py-4">Failed to load GIFs</div>');
        });
}

// Search GIFs
function searchGifs(searchTerm, offset = 0, append = false) {
    const resultsGrid = $('#gifResultsGrid');
    
    if (!append) {
        resultsGrid.html('<div class="gif-loading"><div class="spinner-border" role="status"></div><div class="mt-2">Searching GIFs...</div></div>');
        gifSearchOffset = 0;
    }
    axios.get(base_url + '/webapi/gifs/search', { params: { q: searchTerm, provider: 'giphy', limit: 24, offset } })
        .then(res => {
            if (res.data && res.data.status === 200) {
                const items = res.data.data;
        if (append) {
                    appendGifs(items, resultsGrid);
        } else {
                    displayGifs(items, resultsGrid);
        }
                if (items.length > 0) {
            $('#gifLoadMore').show();
        }
            } else {
                resultsGrid.html('<div class="text-center text-muted py-4">No GIFs found</div>');
            }
        })
        .catch(() => {
            resultsGrid.html('<div class="text-center text-muted py-4">No GIFs found</div>');
        });
}

// Generate mock GIF data (replace with actual Giphy API)
// removed generateMockGifs; use provider-backed results

// Display GIFs in grid
function displayGifs(gifs, container) {
    if (gifs.length === 0) {
        container.html('<div class="text-center text-muted py-4">No GIFs found</div>');
        return;
    }
    
    let gifsHtml = '';
    gifs.forEach(gif => {
        gifsHtml += `
            <div class="gif-item" data-gif='${JSON.stringify(gif)}'>
                <img src="${String(gif.preview).replace(/^http:\/\//,'https://')}" alt="${escapeHtml(gif.title)}" loading="lazy" referrerpolicy="no-referrer" decoding="async">
                <div class="gif-item-overlay">
                    <i class="bi bi-plus-circle"></i>
                </div>
            </div>
        `;
    });
    
    container.html(gifsHtml);
}

// Append GIFs to existing grid
function appendGifs(gifs, container) {
    let gifsHtml = '';
    gifs.forEach(gif => {
        gifsHtml += `
            <div class="gif-item" data-gif='${JSON.stringify(gif)}'>
                <img src="${String(gif.preview).replace(/^http:\/\//,'https://')}" alt="${escapeHtml(gif.title)}" loading="lazy" referrerpolicy="no-referrer" decoding="async">
                <div class="gif-item-overlay">
                    <i class="bi bi-plus-circle"></i>
                </div>
            </div>
        `;
    });
    
    container.append(gifsHtml);
}

// Select GIF
function selectGif(gifData) {
    selectedGif = gifData;
    
    // Show selected GIF preview
    $('#selectedGifContent').html(`
        <img src="${String(gifData.url).replace(/^http:\/\//,'https://')}" alt="${escapeHtml(gifData.title)}" class="img-fluid" loading="lazy" referrerpolicy="no-referrer" decoding="async">
        <div class="text-center mt-2">
            <small class="text-muted">${escapeHtml(gifData.title)}</small>
        </div>
    `);
    
    $('#selectedGifPreview').show();
    
    // Add GIF badge to post area
    showGifBadge(gifData.title, gifData.url);
}

// Show GIF badge in post area
function showGifBadge(gifTitle, gifUrl) {
    const gifBadge = `
        <div class="selected-gif-badge d-inline-flex align-items-center bg-light rounded-pill px-3 py-1 me-2 mb-2">
            <img src="${gifUrl}" alt="${gifTitle}" class="rounded me-2" style="width: 24px; height: 24px; object-fit: cover;">
            <div class="gif-badge-content">
                <div class="gif-badge-title">${gifTitle}</div>
            </div>
            <button type="button" class="btn-close btn-close-sm ms-2" onclick="removeSelectedGif()"></button>
        </div>
    `;
    
    // Add to post area
    $('.post-input-container').append(gifBadge);
}

// Remove selected GIF
function removeSelectedGif() {
    selectedGif = null;
    $('#selectedGifPreview').hide();
    $('.selected-gif-badge').remove();
}

// Reset GIF form
function resetGifForm() {
    selectedGif = null;
    gifSearchOffset = 0;
    currentGifSearchTerm = '';
    $('#gifSearch').val('');
    $('#gifResults').hide();
    $('#selectedGifPreview').hide();
    $('.selected-gif-badge').remove();
}

// Voice Note Functionality Variables
let mediaRecorder = null;
let audioChunks = [];
let isRecording = false;
let isPaused = false;
let recordingStartTime = 0;
let recordingTimer = null;
let recordedAudioBlob = null;

// Initialize Voice Note Section
function initVoiceNoteSection() {
    // Reset recording state
    resetVoiceNoteRecording();
    
    // Request microphone permission
    requestMicrophonePermission();
}

// Request microphone permission
function requestMicrophonePermission() {
    navigator.mediaDevices.getUserMedia({ audio: true })
        .then(function(stream) {
            console.log('Microphone permission granted');
            // Store stream for later use
            window.audioStream = stream;
        })
        .catch(function(err) {
            console.error('Microphone permission denied:', err);
            myAlert.fire({
                icon: 'error',
                title: 'Microphone Access Required',
                text: 'Please allow microphone access to record voice notes.'
            });
        });
}

// Reset voice note recording
function resetVoiceNoteRecording() {
    isRecording = false;
    isPaused = false;
    audioChunks = [];
    recordedAudioBlob = null;
    
    // Reset UI
    $('#recordingText').text('Ready to record');
    $('#timerDisplay').text('00:00');
    $('#recordingIndicator').removeClass('recording');
    $('#recordingVisualization').hide();
    $('#recordedAudioPreview').hide();
    
    // Show/hide buttons
    $('#startRecording').show();
    $('#stopRecording').hide();
    $('#pauseRecording').hide();
    $('#resumeRecording').hide();
    
    // Clear timer
    if (recordingTimer) {
        clearInterval(recordingTimer);
        recordingTimer = null;
    }
}

// Start recording
function startRecording() {
    if (!window.audioStream) {
        myAlert.fire({
            icon: 'error',
            title: 'Microphone Not Available',
            text: 'Please allow microphone access to record voice notes.'
        });
        return;
    }
    
    try {
        mediaRecorder = new MediaRecorder(window.audioStream);
        audioChunks = [];
        
        mediaRecorder.ondataavailable = function(event) {
            audioChunks.push(event.data);
        };
        
        mediaRecorder.onstop = function() {
            recordedAudioBlob = new Blob(audioChunks, { type: 'audio/wav' });
            const audioUrl = URL.createObjectURL(recordedAudioBlob);
            $('#recordedAudio').attr('src', audioUrl);
            $('#recordedAudioPreview').show();
        };
        
        mediaRecorder.start();
        isRecording = true;
        recordingStartTime = Date.now();
        
        // Update UI
        $('#recordingText').text('Recording...');
        $('#recordingIndicator').addClass('recording');
        $('#recordingVisualization').show();
        $('#startRecording').hide();
        $('#stopRecording').show();
        $('#pauseRecording').show();
        
        // Start timer
        startRecordingTimer();
        
    } catch (error) {
        console.error('Error starting recording:', error);
        myAlert.fire({
            icon: 'error',
            title: 'Recording Error',
            text: 'Failed to start recording. Please try again.'
        });
    }
}

// Stop recording
function stopRecording() {
    if (mediaRecorder && isRecording) {
        mediaRecorder.stop();
        isRecording = false;
        isPaused = false;
        
        // Update UI
        $('#recordingText').text('Recording saved');
        $('#recordingIndicator').removeClass('recording');
        $('#recordingVisualization').hide();
        $('#stopRecording').hide();
        $('#pauseRecording').hide();
        $('#resumeRecording').hide();
        
        // Stop timer
        if (recordingTimer) {
            clearInterval(recordingTimer);
            recordingTimer = null;
        }
    }
}

// Pause recording
function pauseRecording() {
    if (mediaRecorder && isRecording && !isPaused) {
        mediaRecorder.pause();
        isPaused = true;
        
        // Update UI
        $('#recordingText').text('Recording paused');
        $('#recordingIndicator').removeClass('recording');
        $('#pauseRecording').hide();
        $('#resumeRecording').show();
        
        // Pause timer
        if (recordingTimer) {
            clearInterval(recordingTimer);
            recordingTimer = null;
        }
    }
}

// Resume recording
function resumeRecording() {
    if (mediaRecorder && isRecording && isPaused) {
        mediaRecorder.resume();
        isPaused = false;
        
        // Update UI
        $('#recordingText').text('Recording...');
        $('#recordingIndicator').addClass('recording');
        $('#resumeRecording').hide();
        $('#pauseRecording').show();
        
        // Resume timer
        startRecordingTimer();
    }
}

// Start recording timer
function startRecordingTimer() {
    recordingTimer = setInterval(function() {
        const elapsed = Date.now() - recordingStartTime;
        const minutes = Math.floor(elapsed / 60000);
        const seconds = Math.floor((elapsed % 60000) / 1000);
        $('#timerDisplay').text(
            (minutes < 10 ? '0' : '') + minutes + ':' + 
            (seconds < 10 ? '0' : '') + seconds
        );
        
        // Stop recording after 5 minutes
        if (elapsed >= 300000) { // 5 minutes
            stopRecording();
            myAlert.fire({
                icon: 'info',
                title: 'Recording Time Limit',
                text: 'Recording stopped automatically after 5 minutes.'
            });
        }
    }, 1000);
}

// Save recorded audio
function saveRecordedAudio() {
    if (recordedAudioBlob) {
        // Create a file from the blob
        const audioFile = new File([recordedAudioBlob], `voice_note_${Date.now()}.wav`, {
            type: 'audio/wav'
        });
        
        // Add to mediaFiles array
        mediaFiles.push(audioFile);
        updateMediaPreview();
        
        // Show success message
        myAlert.fire({
            icon: 'success',
            title: 'Voice Note Saved',
            text: 'Your voice note has been added to the post.'
        });
        
        // Reset recording
        resetVoiceNoteRecording();
        
        // Hide voice note section
        $('#voiceNoteSection').slideUp(300);
    }
}

// Delete recorded audio
function deleteRecordedAudio() {
    recordedAudioBlob = null;
    $('#recordedAudioPreview').hide();
    resetVoiceNoteRecording();
}

// Reset voice note form
function resetVoiceNoteForm() {
    resetVoiceNoteRecording();
    recordedAudioBlob = null;
    $('#recordedAudioPreview').hide();
}

// File Upload Functionality Variables
let selectedFiles = [];
let currentFileFilter = 'all';

// File type configurations
const fileTypes = {
    document: {
        extensions: ['pdf', 'doc', 'docx', 'txt', 'rtf', 'odt'],
        mimeTypes: ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain', 'application/rtf', 'application/vnd.oasis.opendocument.text'],
        icon: 'bi-file-earmark-text',
        color: 'document'
    },
    image: {
        extensions: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp'],
        mimeTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/svg+xml', 'image/webp'],
        icon: 'bi-file-earmark-image',
        color: 'image'
    },
    video: {
        extensions: ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'],
        mimeTypes: ['video/mp4', 'video/x-msvideo', 'video/quicktime', 'video/x-ms-wmv', 'video/x-flv', 'video/webm', 'video/x-matroska'],
        icon: 'bi-file-earmark-play',
        color: 'video'
    },
    audio: {
        extensions: ['mp3', 'wav', 'm4a', 'aac', 'ogg', 'flac'],
        mimeTypes: ['audio/mpeg', 'audio/wav', 'audio/mp4', 'audio/aac', 'audio/ogg', 'audio/flac'],
        icon: 'bi-file-earmark-music',
        color: 'audio'
    },
    archive: {
        extensions: ['zip', 'rar', '7z', 'tar', 'gz'],
        mimeTypes: ['application/zip', 'application/x-rar-compressed', 'application/x-7z-compressed', 'application/x-tar', 'application/gzip'],
        icon: 'bi-file-earmark-zip',
        color: 'archive'
    }
};

// Initialize File Upload Section
function initFileUploadSection() {
    selectedFiles = [];
    currentFileFilter = 'all';
    updateFileList();
    updateFilterButtons();
}

// Get file type category
function getFileType(file) {
    const extension = file.name.split('.').pop().toLowerCase();
    
    for (const [type, config] of Object.entries(fileTypes)) {
        if (config.extensions.includes(extension) || config.mimeTypes.includes(file.type)) {
            return type;
        }
    }
    return 'other';
}

// Format file size
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// Validate file
function validateFile(file) {
    const maxSize = 50 * 1024 * 1024; // 50MB
    
    if (file.size > maxSize) {
        myAlert.fire({
            icon: 'error',
            title: 'File Too Large',
            text: `${file.name} is too large. Maximum file size is 50MB.`
        });
        return false;
    }
    
    return true;
}

// Add files to selection
function addFiles(files) {
    Array.from(files).forEach(file => {
        if (validateFile(file)) {
            // Check if file already exists
            const exists = selectedFiles.some(f => f.name === file.name && f.size === file.size);
            if (!exists) {
                selectedFiles.push(file);
            } else {
                myAlert.fire({
                    icon: 'warning',
                    title: 'File Already Selected',
                    text: `${file.name} is already in the selection.`
                });
            }
        }
    });
    
    updateFileList();
}

// Update file list display
function updateFileList() {
    const container = $('#filesContainer');
    container.empty();
    
    if (selectedFiles.length === 0) {
        $('#uploadedFilesList').hide();
        return;
    }
    
    $('#uploadedFilesList').show();
    
    const filteredFiles = currentFileFilter === 'all' 
        ? selectedFiles 
        : selectedFiles.filter(file => getFileType(file) === currentFileFilter);
    
    filteredFiles.forEach((file, index) => {
        const fileType = getFileType(file);
        const fileTypeConfig = fileTypes[fileType] || { icon: 'bi-file-earmark', color: 'other' };
        
        const fileItem = `
            <div class="file-item" data-index="${index}">
                <div class="file-icon ${fileTypeConfig.color}">
                    <i class="${fileTypeConfig.icon}"></i>
                </div>
                <div class="file-details">
                    <div class="file-name">${file.name}</div>
                    <div class="file-info">
                        <span class="file-size">${formatFileSize(file.size)}</span>
                        <span class="file-type">${fileType.toUpperCase()}</span>
                    </div>
                </div>
                <div class="file-actions">
                    <button type="button" class="btn btn-sm btn-outline-danger remove-file" data-index="${index}">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        `;
        container.append(fileItem);
    });
}

// Update filter buttons
function updateFilterButtons() {
    $('.filter-btn').removeClass('active');
    $(`.filter-btn[data-filter="${currentFileFilter}"]`).addClass('active');
}

// Remove file from selection
function removeFile(index) {
    selectedFiles.splice(index, 1);
    updateFileList();
}

// Clear all files
function clearAllFiles() {
    selectedFiles = [];
    updateFileList();
}

// Add files to post
function addFilesToPost() {
    if (selectedFiles.length === 0) {
        myAlert.fire({
            icon: 'warning',
            title: 'No Files Selected',
            text: 'Please select at least one file to add to the post.'
        });
        return;
    }
    
    // Add files to mediaFiles array
    selectedFiles.forEach(file => {
        mediaFiles.push(file);
    });
    
    updateMediaPreview();
    
    // Show success message
    myAlert.fire({
        icon: 'success',
        title: 'Files Added',
        text: `${selectedFiles.length} file(s) have been added to the post.`
    });
    
    // Reset file upload
    clearAllFiles();
    
    // Hide file upload section
    $('#fileUploadSection').slideUp(300);
}

// Reset file upload form
function resetFileUploadForm() {
    clearAllFiles();
    currentFileFilter = 'all';
    updateFilterButtons();
}

// Tag People Functionality Variables
let taggedPeople = [];
let peopleSuggestions = [];
let searchTimeout = null;

// Initialize Tag People Section
function initTagPeopleSection() {
    taggedPeople = [];
    updateTaggedPeopleList();
    loadPeopleSuggestions();
    $('#searchPeople').val('');
    $('#searchResults').hide();
    $('#peopleSuggestions').show();
}

// Load people suggestions
function loadPeopleSuggestions() {
    const suggestionsList = $('#suggestionsList');
    suggestionsList.html('<div class="people-loading"><div class="spinner-border" role="status"></div><div class="mt-2">Loading suggestions...</div></div>');
    axios.get(base_url + '/webapi/friends/get-all', { params: { limit: 20 } })
        .then(res => {
            if (res.data && Array.isArray(res.data.data)) {
                const users = res.data.data.map(u => ({
                    id: u.id,
                    name: u.name || (u.first_name ? (u.first_name + ' ' + (u.last_name || '')) : (u.username || 'User')),
                    username: u.username ? '@' + u.username : '',
                    avatar: u.avatar || (u.profile ? u.profile : ''),
                    isOnline: !!u.is_online,
                    mutualFriends: u.mutual_friends || 0,
                }));
                displayPeopleList(users, suggestionsList);
            } else if (res.data && res.data.users) {
                const arr = res.data.users;
                const users = arr.map(u => ({
                    id: u.id,
                    name: u.name || u.full_name || u.username,
                    username: u.username ? '@' + u.username : '',
                    avatar: u.avatar || '',
                    isOnline: !!u.is_online,
                    mutualFriends: u.mutual_friends || 0,
                }));
                displayPeopleList(users, suggestionsList);
            } else {
                suggestionsList.html('<div class="text-center text-muted py-3">No suggestions found</div>');
            }
        })
        .catch(() => {
            // Fallback to existing suggestions endpoint if available
            axios.get(base_url + '/webapi/suggested-users')
                .then(res2 => {
                    if (res2.data && Array.isArray(res2.data.users)) {
                        const users = res2.data.users.map(u => ({
                            id: u.id,
                            name: u.name || u.full_name || u.username,
                            username: u.username ? '@' + u.username : '',
                            avatar: u.avatar || '',
                            isOnline: !!u.is_online,
                            mutualFriends: u.mutual_friends || 0,
                        }));
                        displayPeopleList(users, suggestionsList);
                    } else {
                        suggestionsList.html('<div class="text-center text-muted py-3">No suggestions found</div>');
                    }
                })
                .catch(() => {
                    suggestionsList.html('<div class="text-center text-muted py-3">Failed to load suggestions</div>');
                });
        });
}

// Generate mock people suggestions (replace with actual API call)
function generateMockPeopleSuggestions() {
    const mockPeople = [
        {
            id: 1,
            name: 'John Doe',
            username: '@johndoe',
            avatar: 'https://via.placeholder.com/40x40/2196f3/ffffff?text=JD',
            isOnline: true,
            mutualFriends: 5
        },
        {
            id: 2,
            name: 'Jane Smith',
            username: '@janesmith',
            avatar: 'https://via.placeholder.com/40x40/e91e63/ffffff?text=JS',
            isOnline: false,
            mutualFriends: 3
        },
        {
            id: 3,
            name: 'Mike Johnson',
            username: '@mikejohnson',
            avatar: 'https://via.placeholder.com/40x40/4caf50/ffffff?text=MJ',
            isOnline: true,
            mutualFriends: 8
        },
        {
            id: 4,
            name: 'Sarah Wilson',
            username: '@sarahwilson',
            avatar: 'https://via.placeholder.com/40x40/ff9800/ffffff?text=SW',
            isOnline: false,
            mutualFriends: 2
        },
        {
            id: 5,
            name: 'David Brown',
            username: '@davidbrown',
            avatar: 'https://via.placeholder.com/40x40/9c27b0/ffffff?text=DB',
            isOnline: true,
            mutualFriends: 6
        }
    ];
    
    return mockPeople;
}

// Search people
function searchPeople(searchTerm) {
    const resultsList = $('#resultsList');
    resultsList.html('<div class="people-loading"><div class="spinner-border" role="status"></div><div class="mt-2">Searching...</div></div>');
    axios.get(base_url + '/webapi/friends/get-all', { params: { q: searchTerm, limit: 20 } })
        .then(res => {
            let users = [];
            if (res.data && Array.isArray(res.data.data)) {
                users = res.data.data;
            } else if (res.data && Array.isArray(res.data.users)) {
                users = res.data.users;
            }
            const mapped = users.map(u => ({
                id: u.id,
                name: u.name || (u.first_name ? (u.first_name + ' ' + (u.last_name || '')) : (u.username || 'User')),
                username: u.username ? '@' + u.username : '',
                avatar: u.avatar || (u.profile ? u.profile : ''),
                isOnline: !!u.is_online,
                mutualFriends: u.mutual_friends || 0,
            }));
            if (mapped.length === 0) {
                resultsList.html('<div class="text-center text-muted py-3">No users found</div>');
            } else {
                displayPeopleList(mapped, resultsList);
            }
        })
        .catch(() => {
            resultsList.html('<div class="text-center text-muted py-3">Search failed</div>');
        });
}

// Generate mock search results
function generateMockSearchResults(searchTerm) {
    const allPeople = generateMockPeopleSuggestions();
    return allPeople.filter(person => 
        person.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        person.username.toLowerCase().includes(searchTerm.toLowerCase())
    );
}

// Display people list
function displayPeopleList(people, container) {
    if (people.length === 0) {
        container.html(`
            <div class="no-results">
                <i class="bi bi-people"></i>
                <div>No people available</div>
            </div>
        `);
        return;
    }
    
    let peopleHtml = '';
    people.forEach(person => {
        const isTagged = taggedPeople.some(tagged => tagged.id === person.id);
        const statusClass = person.isOnline ? '' : 'offline';
        
        peopleHtml += `
            <div class="person-item ${isTagged ? 'selected' : ''}" data-person-id="${person.id}">
                <img src="${person.avatar}" alt="${person.name}" class="person-avatar">
                <div class="person-details">
                    <div class="person-name">${person.name}</div>
                    <div class="person-info">
                        <span class="person-username">${person.username}</span>
                        <span class="person-status">
                            <span class="status-indicator ${statusClass}"></span>
                            ${person.isOnline ? 'Online' : 'Offline'}
                        </span>
                        <span>${person.mutualFriends} mutual friends</span>
                    </div>
                </div>
                <div class="person-actions">
                    ${isTagged ? 
                        `<button type="button" class="btn btn-sm btn-outline-danger remove-person-tag" data-person-id="${person.id}">
                            <i class="bi bi-x"></i> Remove
                        </button>` :
                        `<button type="button" class="btn btn-sm btn-outline-primary add-person-tag" data-person-id="${person.id}">
                            <i class="bi bi-plus"></i> Tag
                        </button>`
                    }
                </div>
            </div>
        `;
    });
    
    container.html(peopleHtml);
}

// Add person to tagged list
function addPersonToTagged(personId) {
    const person = findPersonById(personId);
    if (person && !taggedPeople.some(tagged => tagged.id === personId)) {
        taggedPeople.push(person);
        updateTaggedPeopleList();
        updatePeopleLists();
    }
}

// Remove person from tagged list
function removePersonFromTagged(personId) {
    taggedPeople = taggedPeople.filter(person => person.id !== personId);
    updateTaggedPeopleList();
    updatePeopleLists();
}

// Find person by ID
function findPersonById(personId) {
    // Search from currently displayed lists first
    let person = null;
    const $listItems = $('#peopleSuggestions .person-item, #resultsList .person-item');
    $listItems.each(function() {
        const id = parseInt($(this).data('person-id'));
        if (id === personId) {
            const name = $(this).find('.person-name').text();
            const username = $(this).find('.person-username').text();
            const avatar = $(this).find('.person-avatar').attr('src');
            person = { id: personId, name, username, avatar, isOnline: false, mutualFriends: 0 };
            return false;
        }
    });
    return person;
}

// Update tagged people list
function updateTaggedPeopleList() {
    const container = $('#taggedPeopleList');
    container.empty();
    
    if (taggedPeople.length === 0) {
        $('#selectedPeople').hide();
        return;
    }
    
    $('#selectedPeople').show();
    
    taggedPeople.forEach(person => {
        const taggedPersonHtml = `
            <div class="tagged-person" data-person-id="${person.id}">
                <img src="${person.avatar}" alt="${person.name}" class="tagged-person-avatar">
                <span class="tagged-person-name">${person.name}</span>
                <button type="button" class="remove-tag" data-person-id="${person.id}">
                    <i class="bi bi-x"></i>
                </button>
            </div>
        `;
        container.append(taggedPersonHtml);
    });
}

// Update all people lists
function updatePeopleLists() {
    // Update suggestions list
    const suggestions = generateMockPeopleSuggestions();
    displayPeopleList(suggestions, $('#suggestionsList'));
    
    // Update search results if visible
    if ($('#searchResults').is(':visible')) {
        const searchTerm = $('#searchPeople').val();
        const searchResults = generateMockSearchResults(searchTerm);
        displayPeopleList(searchResults, $('#resultsList'));
    }
}

// Save tags
function saveTags() {
    if (taggedPeople.length === 0) {
        myAlert.fire({
            icon: 'warning',
            title: 'No People Tagged',
            text: 'Please tag at least one person before saving.'
        });
        return;
    }
    
    // Show success message
    myAlert.fire({
        icon: 'success',
        title: 'People Tagged',
        text: `${taggedPeople.length} person(s) have been tagged in the post.`
    });
    
    // Add tagged people to post area
    showTaggedPeopleInPost();
    
    // Hide tag people section
    $('#tagPeopleSection').slideUp(300);
}

// Show tagged people in post area
function showTaggedPeopleInPost() {
    const taggedPeopleHtml = `
        <div class="tagged-people-badge d-inline-flex align-items-center bg-light rounded-pill px-3 py-1 me-2 mb-2">
            <i class="bi bi-person-plus text-primary me-2"></i>
            <div class="tagged-people-content">
                <div class="tagged-people-title">${taggedPeople.length} person(s) tagged</div>
            </div>
            <button type="button" class="btn-close btn-close-sm ms-2" onclick="removeTaggedPeopleFromPost()"></button>
        </div>
    `;
    
    // Add to post area
    $('.post-input-container').append(taggedPeopleHtml);
}

// Remove tagged people from post
function removeTaggedPeopleFromPost() {
    $('.tagged-people-badge').remove();
    taggedPeople = [];
}

// Clear all tags
function clearAllTags() {
    taggedPeople = [];
    updateTaggedPeopleList();
    updatePeopleLists();
    $('.tagged-people-badge').remove();
}

// Reset tag people form
function resetTagPeopleForm() {
    clearAllTags();
    $('#searchPeople').val('');
    $('#searchResults').hide();
    $('#peopleSuggestions').show();
}

// Post Options Functionality Variables
let isScheduled = false;
let isAnonymous = false;
let isTipsEnabled = false;
let scheduledDateTime = null;

// Initialize Post Options
function initPostOptions() {
    // Reset all options
    isScheduled = false;
    isAnonymous = false;
    isTipsEnabled = false;
    scheduledDateTime = null;
    
    // Reset UI
    $('#is_schedule').prop('checked', false);
    $('#is_anonymous').prop('checked', false);
    $('#tips_enabled').prop('checked', false);
    $('#schedule-datetime-wrapper').hide();
    $('.js_publisher-schedule-date').val('');
}

// Handle Schedule Post Toggle
function handleScheduleToggle() {
    isScheduled = $('#is_schedule').is(':checked');
    
    if (isScheduled) {
        $('#schedule-datetime-wrapper').slideDown(300);
        // Set minimum date to current date + 1 hour
        const now = new Date();
        now.setHours(now.getHours() + 1);
        const minDateTime = now.toISOString().slice(0, 16);
        $('.js_publisher-schedule-date').attr('min', minDateTime);
    } else {
        $('#schedule-datetime-wrapper').slideUp(300);
        scheduledDateTime = null;
    }
}

// Handle Anonymous Post Toggle
function handleAnonymousToggle() {
    isAnonymous = $('#is_anonymous').is(':checked');
    
    if (isAnonymous) {
        // Show confirmation dialog
        myAlert.fire({
            icon: 'warning',
            title: 'Anonymous Post',
            text: 'This post will be shared anonymously. Your identity will be hidden.',
            showCancelButton: true,
            confirmButtonText: 'Continue',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (!result.isConfirmed) {
                $('#is_anonymous').prop('checked', false);
                isAnonymous = false;
            }
        });
    }
}

// Handle Tips Toggle
function handleTipsToggle() {
    isTipsEnabled = $('#tips_enabled').is(':checked');
    
    if (isTipsEnabled) {
        // Show tips info
        myAlert.fire({
            icon: 'info',
            title: 'Tips Enabled',
            text: 'People can now send you tips for this post. Tips will be added to your wallet.',
            confirmButtonText: 'OK'
        });
    }
}



// Reset Post Options
function resetPostOptions() {
    initPostOptions();
}

// AI Features Variables
let selectedPostStyle = 'casual';
let selectedImageStyle = 'realistic';
let selectedImageSize = '512x512';
let generatedPostContent = '';
let generatedImageUrl = '';

// Initialize AI Features
function initAIFeatures() {
    selectedPostStyle = 'casual';
    selectedImageStyle = 'realistic';
    selectedImageSize = '512x512';
    generatedPostContent = '';
    generatedImageUrl = '';
    
    // Reset UI
    $('#aiPostSection').hide();
    $('#aiImageSection').hide();
    $('#aiPostPrompt').val('');
    $('#aiImagePrompt').val('');
    $('#generatedPostPreview').hide();
    $('#generatedImagePreview').hide();
    
    // Reset style buttons
    $('.ai-style-btn').removeClass('active');
    $('.ai-style-btn[data-style="casual"]').addClass('active');
    
    $('.ai-image-style-btn').removeClass('active');
    $('.ai-image-style-btn[data-style="realistic"]').addClass('active');
    
    $('.ai-size-btn').removeClass('active');
    $('.ai-size-btn[data-size="512x512"]').addClass('active');
}

// AI Post Generation via backend
async function generateAIPost(prompt, style) {
    const resp = await axios.post(base_url + '/webapi/ai/generate-post', { prompt, style });
    if (resp.data && resp.data.status === 200 && resp.data.data && resp.data.data.content) {
        return resp.data.data.content;
    }
    throw new Error('Failed to generate');
}

// AI Image Generation via backend
async function generateAIImage(prompt, style, size) {
    const resp = await axios.post(base_url + '/webapi/ai/generate-image', { prompt, style, size });
    if (resp.data && resp.data.status === 200 && resp.data.data && resp.data.data.url) {
        return resp.data.data.url;
    }
    throw new Error('Failed to generate image');
}

// Handle AI Post Generation
async function handleAIPostGeneration() {
    const prompt = $('#aiPostPrompt').val().trim();
    
    if (!prompt) {
        myAlert.fire({
            icon: 'warning',
            title: 'Prompt Required',
            text: 'Please enter a description of the post you want to generate.'
        });
        return;
    }
    
    // Show loading state
    const generateBtn = $('#generatePostBtn');
    const originalText = generateBtn.html();
    generateBtn.html('<span class="ai-loading me-2"></span>Generating...');
    generateBtn.prop('disabled', true);
    
    try {
        const generatedPost = await generateAIPost(prompt, selectedPostStyle);
        generatedPostContent = generatedPost;
        
        // Display generated post
        $('#generatedContent').html(generatedPost.replace(/\n/g, '<br>'));
        $('#generatedPostPreview').slideDown(300);
        
        myAlert.fire({
            icon: 'success',
            title: 'Post Generated!',
            text: 'Your AI-generated post is ready. You can use it or regenerate if needed.'
        });
        
    } catch (error) {
        myAlert.fire({
            icon: 'error',
            title: 'Generation Failed',
            text: 'Failed to generate post. Please try again.'
        });
    } finally {
        // Reset button
        generateBtn.html(originalText);
        generateBtn.prop('disabled', false);
    }
}

// Handle AI Image Generation
async function handleAIImageGeneration() {
    const prompt = $('#aiImagePrompt').val().trim();
    
    if (!prompt) {
        myAlert.fire({
            icon: 'warning',
            title: 'Prompt Required',
            text: 'Please enter a description of the image you want to generate.'
        });
        return;
    }
    
    // Show loading state
    const generateBtn = $('#generateImageBtn');
    const originalText = generateBtn.html();
    generateBtn.html('<span class="ai-loading me-2"></span>Generating...');
    generateBtn.prop('disabled', true);
    
    try {
        const generatedImage = await generateAIImage(prompt, selectedImageStyle, selectedImageSize);
        generatedImageUrl = generatedImage;
        
        // Display generated image
        $('#generatedImage').attr('src', generatedImage);
        $('#generatedImagePreview').slideDown(300);
        
        myAlert.fire({
            icon: 'success',
            title: 'Image Generated!',
            text: 'Your AI-generated image is ready. You can use it, regenerate, or download it.'
        });
        
    } catch (error) {
        myAlert.fire({
            icon: 'error',
            title: 'Generation Failed',
            text: 'Failed to generate image. Please try again.'
        });
    } finally {
        // Reset button
        generateBtn.html(originalText);
        generateBtn.prop('disabled', false);
    }
}

// Use Generated Post
function useGeneratedPost() {
    if (generatedPostContent) {
        $('#postInput').val(generatedPostContent);
        $('#aiPostSection').slideUp(300);
        myAlert.fire({
            icon: 'success',
            title: 'Post Added!',
            text: 'The generated post has been added to your post input.'
        });
    }
}

// Use Generated Image
function useGeneratedImage() {
    if (generatedImageUrl) {
        // Create a file object from the image URL
        fetch(generatedImageUrl)
            .then(response => response.blob())
            .then(blob => {
                const file = new File([blob], 'ai-generated-image.jpg', { type: 'image/jpeg' });
                mediaFiles.push(file);
                updateMediaPreview();
                $('#aiImageSection').slideUp(300);
                myAlert.fire({
                    icon: 'success',
                    title: 'Image Added!',
                    text: 'The generated image has been added to your post.'
                });
            })
            .catch(error => {
                myAlert.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Failed to add image to post. Please try again.'
                });
            });
    }
}

// Download Generated Image
function downloadGeneratedImage() {
    if (generatedImageUrl) {
        const link = document.createElement('a');
        link.href = generatedImageUrl;
        link.download = 'ai-generated-image.jpg';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}

// Reset AI Post Form
function resetAIPostForm() {
    $('#aiPostPrompt').val('');
    $('#generatedPostPreview').hide();
    generatedPostContent = '';
    $('.ai-style-btn').removeClass('active');
    $('.ai-style-btn[data-style="casual"]').addClass('active');
    selectedPostStyle = 'casual';
}

// Reset AI Image Form
function resetAIImageForm() {
    $('#aiImagePrompt').val('');
    $('#generatedImagePreview').hide();
    generatedImageUrl = '';
    $('.ai-image-style-btn').removeClass('active');
    $('.ai-image-style-btn[data-style="realistic"]').addClass('active');
    $('.ai-size-btn').removeClass('active');
    $('.ai-size-btn[data-size="512x512"]').addClass('active');
    selectedImageStyle = 'realistic';
    selectedImageSize = '512x512';
}

// Enhanced Post Input Validation
function validatePostInput() {
    const postText = $("#postInput").val().trim();
    const charCount = postText.length;
    const maxChars = 5000;
    
    // Update character counter
    updateCharacterCounter(charCount, maxChars);
    
    // Check for excessive whitespace
    if (postText && /^\s+$/.test(postText)) {
        return {
            isValid: false,
            message: 'Post cannot contain only whitespace.'
        };
    }
    
    // Check for excessive line breaks
    const lineBreaks = (postText.match(/\n/g) || []).length;
    if (lineBreaks > 50) {
        return {
            isValid: false,
            message: 'Post contains too many line breaks.'
        };
    }
    
    // Check for excessive emojis
    const emojiCount = (postText.match(/[\u{1F600}-\u{1F64F}]|[\u{1F300}-\u{1F5FF}]|[\u{1F680}-\u{1F6FF}]|[\u{1F1E0}-\u{1F1FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu) || []).length;
    if (emojiCount > 20) {
        return {
            isValid: false,
            message: 'Post contains too many emojis.'
        };
    }
    
    return {
        isValid: true,
        charCount: charCount,
        maxChars: maxChars
    };
}

function updateCharacterCounter(charCount, maxChars) {
    const counter = $('#charCounter');
    if (counter.length === 0) {
        // Create character counter if it doesn't exist
        $('#postInput').after(`<div id="charCounter" class="text-muted small mt-1"></div>`);
    }
    
    const percentage = (charCount / maxChars) * 100;
    let colorClass = 'text-muted';
    
    if (percentage >= 90) {
        colorClass = 'text-danger';
    } else if (percentage >= 75) {
        colorClass = 'text-warning';
    }
    
    $('#charCounter').html(`<span class="${colorClass}">${charCount}/${maxChars} characters</span>`);
}

// Enhanced Media Validation
function validateMediaBeforeUpload(files) {
    const errors = [];
    const maxTotalSize = 100 * 1024 * 1024; // 100MB total
    let totalSize = 0;
    
    Array.from(files).forEach((file, index) => {
        totalSize += file.size;
        
        // Check individual file size
        if (file.size > 50 * 1024 * 1024) {
            errors.push(`File "${file.name}" is too large (${formatFileSize(file.size)}). Maximum size is 50MB.`);
        }
        
        // Check file type
        const allowedTypes = [
            // Images
            'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp',
            // Video
            'video/mp4', 'video/avi', 'video/mov', 'video/wmv', 'video/flv', 'video/webm',
            // Audio
            'audio/mp3', 'audio/mpeg', 'audio/wav', 'audio/ogg', 'audio/m4a', 'audio/aac', 'audio/flac', 'audio/webm',
            // Documents
            'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain', 'application/rtf', 'application/vnd.oasis.opendocument.text',
            // Archives
            'application/zip', 'application/x-rar-compressed', 'application/x-7z-compressed', 'application/x-tar', 'application/gzip'
        ];
        
        if (!allowedTypes.includes(file.type)) {
            errors.push(`File "${file.name}" has an unsupported type (${file.type}).`);
        }
    });
    
    // Check total size
    if (totalSize > maxTotalSize) {
        errors.push(`Total file size (${formatFileSize(totalSize)}) exceeds the maximum limit of 100MB.`);
    }
    
    return {
        isValid: errors.length === 0,
        errors: errors
    };
}

// Form state preservation for error recovery
let preservedFormState = null;

// Function to save current form state as a draft
function saveDraft() {
    preserveFormState();
    myAlert.fire({
        icon: 'success',
        title: 'Draft Saved',
        text: 'Your post has been saved as a draft. You can restore it later.',
        timer: 2000,
        timerProgressBar: true
    });
}

function preserveFormState() {
    preservedFormState = {
        postText: $("#postInput").val(),
        mediaFiles: [...mediaFiles],
        selectedPrivacy: selectedPrivacy,
        selectedLocation: selectedLocation,
        selectedGif: selectedGif,
        selectedBackgroundColor: selectedBackgroundColor,
        selectedTextColor: selectedTextColor,
        selectedFontSize: selectedFontSize,
        taggedPeople: [...taggedPeople],
        isScheduled: isScheduled,
        isAnonymous: isAnonymous,
        isTipsEnabled: isTipsEnabled,
        scheduledDateTime: scheduledDateTime,
        pollData: $('#pollSection').is(':visible') ? {
            question: $('#pollQuestion').val(),
            options: $('#pollOptions .poll-option').map(function() {
                return $(this).find('input').val();
            }).get(),
            allowMultipleVotes: $('#allowMultipleVotes').is(':checked'),
            hideResults: $('#hideResults').is(':checked')
        } : null,
        feelingCategory: $("#feeling-category").val(),
        feelingDescription: $("#feeling-description").val(),
        sectionsVisible: {
            poll: $('#pollSection').is(':visible'),
            location: $('#locationSection').is(':visible'),
            colorPost: $('#colorPostSection').is(':visible'),
            gif: $('#gifSection').is(':visible'),
            voiceNote: $('#voiceNoteSection').is(':visible'),
            fileUpload: $('#fileUploadSection').is(':visible'),
            tagPeople: $('#tagPeopleSection').is(':visible'),
            aiPost: $('#aiPostSection').is(':visible'),
            aiImage: $('#aiImageSection').is(':visible')
        }
    };
}

function restoreFormState() {
    if (!preservedFormState) return;
    
    // Restore main input
    $("#postInput").val(preservedFormState.postText);
    
    // Restore media files
    mediaFiles = [...preservedFormState.mediaFiles];
    updateMediaPreview();
    
    // Restore privacy
    selectedPrivacy = preservedFormState.selectedPrivacy;
    $("#privacyDropdown span").text($(`[data-privacy="${selectedPrivacy}"]`).text().trim());
    
    // Restore location
    if (preservedFormState.selectedLocation) {
        selectedLocation = preservedFormState.selectedLocation;
        showLocationBadge(selectedLocation.name, selectedLocation.address);
    }
    
    // Restore GIF
    if (preservedFormState.selectedGif) {
        selectedGif = preservedFormState.selectedGif;
        showGifBadge(selectedGif.title, selectedGif.url);
    }
    
    // Restore colored post
    if (preservedFormState.selectedBackgroundColor) {
        selectedBackgroundColor = preservedFormState.selectedBackgroundColor;
        selectedTextColor = preservedFormState.selectedTextColor;
        selectedFontSize = preservedFormState.selectedFontSize;
        updateTextareaStyling();
    }
    
    // Restore tagged people
    taggedPeople = [...preservedFormState.taggedPeople];
    updateTaggedPeopleList();
    
    // Restore post options
    isScheduled = preservedFormState.isScheduled;
    isAnonymous = preservedFormState.isAnonymous;
    isTipsEnabled = preservedFormState.isTipsEnabled;
    scheduledDateTime = preservedFormState.scheduledDateTime;
    
    // Restore sections visibility
    if (preservedFormState.sectionsVisible.poll) $('#pollSection').slideDown(300);
    if (preservedFormState.sectionsVisible.location) $('#locationSection').slideDown(300);
    if (preservedFormState.sectionsVisible.colorPost) $('#colorPostSection').slideDown(300);
    if (preservedFormState.sectionsVisible.gif) $('#gifSection').slideDown(300);
    if (preservedFormState.sectionsVisible.voiceNote) $('#voiceNoteSection').slideDown(300);
    if (preservedFormState.sectionsVisible.fileUpload) $('#fileUploadSection').slideDown(300);
    if (preservedFormState.sectionsVisible.tagPeople) $('#tagPeopleSection').slideDown(300);
    if (preservedFormState.sectionsVisible.aiPost) $('#aiPostSection').slideDown(300);
    if (preservedFormState.sectionsVisible.aiImage) $('#aiImageSection').slideDown(300);
    
    // Restore poll data
    if (preservedFormState.pollData) {
        $('#pollQuestion').val(preservedFormState.pollData.question);
        preservedFormState.pollData.options.forEach((option, index) => {
            if (index < 2) {
                $(`#pollOption${index + 1}`).val(option);
            } else {
                addPollOption();
                $(`#pollOption${index + 1}`).val(option);
            }
        });
        $('#allowMultipleVotes').prop('checked', preservedFormState.pollData.allowMultipleVotes);
        $('#hideResults').prop('checked', preservedFormState.pollData.hideResults);
    }
    
    // Restore feeling
    if (preservedFormState.feelingCategory && preservedFormState.feelingDescription) {
        $("#feeling-category").val(preservedFormState.feelingCategory);
        $("#feeling-description").val(preservedFormState.feelingDescription);
        showSelectedFeeling({
            category: preservedFormState.feelingCategory,
            description: preservedFormState.feelingDescription
        });
    }
    
    // Clear preserved state
    preservedFormState = null;
}

// Enhanced Form Reset Function
function resetPostForm() {
    // Reset main input
    $("#postInput").val("");
    $('#charCounter').remove();
    
    // Reset media files
    mediaFiles = [];
    updateMediaPreview();
    
    // Reset all sections
    $('.posting-detail').slideUp(300);
    $('#pollSection').slideUp(300);
    $('#locationSection').slideUp(300);
    $('#colorPostSection').slideUp(300);
    $('#gifSection').slideUp(300);
    $('#voiceNoteSection').slideUp(300);
    $('#fileUploadSection').slideUp(300);
    $('#tagPeopleSection').slideUp(300);
    $('#aiPostSection').slideUp(300);
    $('#aiImageSection').slideUp(300);
    
    // Reset all forms
    resetFeelingSelection();
    resetPollForm();
    resetLocationForm();
    resetColoredPost();
    resetGifForm();
    resetVoiceNoteForm();
    resetFileUploadForm();
    resetTagPeopleForm();
    resetPostOptions();
    resetAIPostForm();
    resetAIImageForm();
    
    // Reset preview area
    $('#preview-area').addClass("d-none").empty();
    
    // Reset button state
    $("#postButton").prop("disabled", false).text("Post");
    
    // Remove highlight
    removeHighlightPost();
}

// Enhanced Error Handling
function handlePostError(error, context = '') {
    console.error(`Post error${context ? ` (${context})` : ''}:`, error);
    
    let errorMessage = 'An unexpected error occurred. Please try again.';
    let errorTitle = 'Error';
    
    // Preserve form state for retry
    preserveFormState();
    
    if (error.response) {
        const status = error.response.status;
        const data = error.response.data;
        
        switch (status) {
            case 401:
                errorTitle = 'Authentication Error';
                errorMessage = 'Please log in again to continue.';
                // Redirect to login
                setTimeout(() => {
                    window.location.href = base_url + '/login';
                }, 2000);
                break;
            case 403:
                errorTitle = 'Permission Denied';
                errorMessage = 'You do not have permission to perform this action.';
                break;
            case 422:
                errorTitle = 'Validation Error';
                errorMessage = data.message || 'Please check your input and try again.';
                break;
            case 429:
                errorTitle = 'Rate Limit Exceeded';
                errorMessage = 'You are posting too frequently. Please wait a moment and try again.';
                break;
            case 500:
                errorTitle = 'Server Error';
                errorMessage = 'Our servers are experiencing issues. Please try again later.';
                break;
            default:
                errorMessage = data.message || `Server error (${status}). Please try again.`;
        }
    } else if (error.request) {
        errorTitle = 'Network Error';
        errorMessage = 'Please check your internet connection and try again.';
    } else if (error.code === 'ECONNABORTED') {
        errorTitle = 'Timeout Error';
        errorMessage = 'The request took too long. Please try again.';
    }
    
    myAlert.fire({
        icon: 'error',
        title: errorTitle,
        text: errorMessage,
        showCancelButton: true,
        confirmButtonText: 'Retry',
        cancelButtonText: 'OK',
        reverseButtons: true
    }).then((result) => {
        if (result.isConfirmed) {
            // Restore form state and retry
            restoreFormState();
            // Trigger post submission again
            $("#postButton").click();
        }
    });
}
    
    // Function to share with specific user
    function shareWithUser(postId) {
        const modalHtml = `
        <div class="modal fade" id="shareUserModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Share with a friend</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <input type="text" class="form-control" placeholder="Search friends...">
                        </div>
                        <div class="user-list">
                            <div class="d-flex align-items-center p-2 border-bottom user-item">
                                <div class="avatar me-3">
                                    <img src="../assets/images/avatar/01.jpg" class="avatar rounded-circle" alt="">
                                </div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-0">John Doe</h6>
                                    <small class="text-muted">Online</small>
                                </div>
                                <button class="btn btn-sm btn-primary">Send</button>
                            </div>
                            <div class="d-flex align-items-center p-2 border-bottom user-item">
                                <div class="avatar me-3">
                                    <img src="../assets/images/avatar/02.jpg" class="avatar rounded-circle" alt="">
                                </div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-0">Jane Smith</h6>
                                    <small class="text-muted">Last active 2h ago</small>
                                </div>
                                <button class="btn btn-sm btn-primary">Send</button>
                            </div>
                            <div class="d-flex align-items-center p-2 user-item">
                                <div class="avatar me-3">
                                    <img src="../assets/images/avatar/03.jpg" class="avatar rounded-circle" alt="">
                                </div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-0">Robert Johnson</h6>
                                    <small class="text-muted">Last active yesterday</small>
                                </div>
                                <button class="btn btn-sm btn-primary">Send</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>`;
        
        // Remove any existing modal
        $('#shareUserModal').remove();
        
        // Add new modal and show it
        $('body').append(modalHtml);
        const modal = new bootstrap.Modal(document.getElementById('shareUserModal'));
        modal.show();
        
        // Add click handler to send buttons
        $(document).on('click', '.user-item button', function() {
            // This would normally send the post via API
            const userName = $(this).closest('.user-item').find('h6').text();
            modal.hide();
            showAlert('success', 'Post Shared', `Post has been sent to ${userName}`);
        });
    }
});

/**
 * Get authentication token (you may need to adapt this based on your auth system)
 */
function getAuthToken() {
    // Return the CSRF token for Laravel session-based authentication
    return $('meta[name="csrf-token"]').attr('content') || '';
}


/**
 * Load user groups from API and update the UI
 */
function loadUserGroups() {
    fetch(base_url+'/webapi/dashboard/user-groups', {
        method: 'GET',
        headers: {
            'X-CSRF-TOKEN': getAuthToken(),
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 200) {
            updateUserGroupsUI(data.data);
        }
    })
    .catch(error => {
        console.error('Error loading user groups:', error);
    });
}

/**
 * Load suggested users from API and update the UI
 */
function loadSuggestedUsers() {
    fetch(base_url+'/api/dashboard/suggested-users', {
        method: 'GET',
        headers: {
            'X-CSRF-TOKEN': getAuthToken(),
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 200) {
            updateSuggestedUsersUI(data.data);
        }
    })
    .catch(error => {
        console.error('Error loading suggested users:', error);
    });
}


/**
 * Update user groups UI based on API data
 */
function updateUserGroupsUI(groups) {
    const groupsContainer = $('.card:has(h6:contains("Your Groups")) .card-body');
    
    if (groups && groups.length > 0) {
        let groupsHtml = '<div class="card-body p-3">';
        
        groups.slice(0, 2).forEach(group => {
            groupsHtml += `
                <div class="mb-3 d-flex align-items-center">
                    <div class="avatar avatar-xs me-2">
                        <img class="avatar rounded-circle" src="${group.cover || '/assets/images/group-1.jpg'}" alt="Group">
                    </div>
                    <div class="overflow-hidden">
                        <a class="h6 mb-0 text-truncate d-block" href="/group/${group.slug}">${group.name}</a>
                        <small class="text-muted">${group.members_count || 0} members</small>
                    </div>
                </div>
            `;
        });
        
        groupsHtml += '<a href="/my-groups" class="btn btn-sm btn-link text-decoration-none">See all groups</a>';
        groupsHtml += '</div>';
        
        groupsContainer.html(groupsHtml);
        
        // Update the create button link
        $('.card:has(h6:contains("Your Groups")) .btn-primary-soft').attr('href', '/group/create');
    } else {
        // No groups found
        const noGroupsHtml = `
            <div class="card-body p-3 text-center">
                <div class="py-4">
                    <i class="bi bi-people-fill text-muted mb-3" style="font-size: 3rem;"></i>
                    <h6 class="text-muted">No groups found</h6>
                    <p class="text-muted small mb-3">Join groups to connect with like-minded people</p>
                    <a href="/group/create" class="btn btn-primary btn-sm">Create New Group</a>
                </div>
            </div>
        `;
        groupsContainer.html(noGroupsHtml);
        
        // Update the create button link
        $('.card:has(h6:contains("Your Groups")) .btn-primary-soft').attr('href', '/group/create');
    }
}

/**
 * Update suggested users UI based on API data
 */
function updateSuggestedUsersUI(users) {
    const followContainer = $('.card:has(h5:contains("Who to Follow")) .card-body');
    
    if (users && users.length > 0) {
        let usersHtml = '';
        
        users.forEach((user, index) => {
            const isLast = index === users.length - 1;
            usersHtml += `
                <div class="hstack gap-2 ${!isLast ? 'mb-3' : ''}">
                    <div class="avatar">
                        <img class="avatar rounded-circle" src="${user.avatar || '/assets/images/avatar/user.jpg'}" alt="${user.name}">
                    </div>
                    <div class="overflow-hidden">
                        <a class="h6 mb-0" href="/profile/${user.username}">${user.name}</a>
                        <p class="mb-0 small text-truncate">@${user.username}</p>
                    </div>
                    <button class="btn btn-primary-soft rounded-circle icon-md ms-auto" onclick="sendFriendRequest(${user.id})">
                        <i class="bi bi-person-plus"></i>
                    </button>
                </div>
            `;
        });
        
        followContainer.html(usersHtml);
    } else {
        // No suggestions available
        const noSuggestionsHtml = `
            <div class="text-center py-3">
                <i class="bi bi-person-plus text-muted mb-2" style="font-size: 2rem;"></i>
                <p class="text-muted small mb-0">No suggestions available</p>
            </div>
        `;
        followContainer.html(noSuggestionsHtml);
    }
}

/**
 * Send friend request to a user
 */
function sendFriendRequest(userId) {
    fetch(base_url+'/api/friends/send-request', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': getAuthToken(),
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({
            friend_two: userId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 200) {
            showAlert('success', 'Friend Request Sent', data.message);
            // Reload suggested users to remove the user we just sent a request to
            loadSuggestedUsers();
        } else {
            showAlert('error', 'Error', data.message || 'Failed to send friend request');
        }
    })
    .catch(error => {
        console.error('Error sending friend request:', error);
        showAlert('error', 'Error', 'Failed to send friend request');
    });
}

// Right Sidebar Widgets Functions
// ===============================

// Load Trending Hashtags
async function loadTrendingHashtags() {
    try {
        const response = await fetch(base_url+'/webapi/trending-hashtags', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            }
        });

        if (!response.ok) {
            throw new Error('Failed to load trending hashtags');
        }

        const data = await response.json();
        const container = document.getElementById('trendingHashtagsList');
        
        if (data.success && data.hashtags && data.hashtags.length > 0) {
            container.innerHTML = data.hashtags.map((hashtag, index) => `
                <div class="hashtag-item" onclick="searchHashtag('${hashtag.name}')">
                    <div class="hashtag-content">
                        <div class="hashtag-icon">
                            <i class="bi bi-hash"></i>
                        </div>
                        <div class="hashtag-details">
                            <div class="hashtag-name">#${hashtag.name}</div>
                            <div class="hashtag-count">${hashtag.count} posts</div>
                        </div>
                    </div>
                    <div class="hashtag-rank">
                        <span class="badge bg-primary">#${index + 1}</span>
                    </div>
                </div>
            `).join('');
        } else {
            container.innerHTML = `
                <div class="empty-state">
                    <i class="bi bi-hash"></i>
                    <h6>No trending hashtags</h6>
                    <p>Check back later for trending topics</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('Error loading trending hashtags:', error);
        const container = document.getElementById('trendingHashtagsList');
        container.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-exclamation-triangle"></i>
                <h6>Error loading hashtags</h6>
                <p>Please try again later</p>
            </div>
        `;
    }
}

// Load Suggested Users
async function loadSuggestedUsers() {
    try {
        const response = await fetch(base_url+'/webapi/suggested-users', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            }
        });

        if (!response.ok) {
            throw new Error('Failed to load suggested users');
        }

        const data = await response.json();
        const container = document.getElementById('suggestedUsersList');
        
        if (data.success && data.users && data.users.length > 0) {
            container.innerHTML = data.users.map(user => `
                <div class="person-item">
                    <img src="${user.avatar || '/assets/images/avatar/default.jpg'}" alt="${user.name}" class="person-avatar">
                    <div class="person-details">
                        <div class="person-name">${user.name}</div>
                        <div class="person-info">${user.mutual_friends || 0} mutual friends</div>
                    </div>
                    <div class="person-actions">
                        <button class="person-btn add" onclick="sendFriendRequest(${user.id})">
                            <i class="bi bi-person-plus"></i>
                        </button>
                    </div>
                </div>
            `).join('');
        } else {
            container.innerHTML = `
                <div class="empty-state">
                    <i class="bi bi-people"></i>
                    <h6>No suggestions</h6>
                    <p>We'll find people for you soon</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('Error loading suggested users:', error);
        const container = document.getElementById('suggestedUsersList');
        container.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-exclamation-triangle"></i>
                <h6>Error loading users</h6>
                <p>Please try again later</p>
            </div>
        `;
    }
}

// Load Suggested Pages
async function loadSuggestedPages() {
    try {
        const response = await fetch(base_url+'/webapi/suggested-pages', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            }
        });

        if (!response.ok) {
            throw new Error('Failed to load suggested pages');
        }

        const data = await response.json();
        const container = document.getElementById('suggestedPagesList');
        
        if (data.success && data.pages && data.pages.length > 0) {
            container.innerHTML = data.pages.map(page => `
                <div class="page-item">
                    <img src="${page.cover_image || '/assets/placeholder/image.png'}" alt="${page.name}" class="page-avatar">
                    <div class="page-details">
                        <div class="page-name">${page.name}</div>
                        <div class="page-info">${page.followers_count || 0} followers</div>
                    </div>
                    <div class="page-actions">
                        <button class="page-btn like" onclick="likePage(${page.id})">
                            <i class="bi bi-heart"></i> Like
                        </button>
                    </div>
                </div>
            `).join('');
        } else {
            container.innerHTML = `
                <div class="empty-state">
                    <i class="bi bi-flag"></i>
                    <h6>No page suggestions</h6>
                    <p>Discover pages based on your interests</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('Error loading suggested pages:', error);
        const container = document.getElementById('suggestedPagesList');
        container.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-exclamation-triangle"></i>
                <h6>Error loading pages</h6>
                <p>Please try again later</p>
            </div>
        `;
    }
}

// Load Suggested Groups
async function loadSuggestedGroups() {
    try {
        const response = await fetch(base_url+'/webapi/suggested-groups', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            }
        });

        if (!response.ok) {
            throw new Error('Failed to load suggested groups');
        }

        const data = await response.json();
        const container = document.getElementById('suggestedGroupsList');
        
        if (data.success && data.groups && data.groups.length > 0) {
            container.innerHTML = data.groups.map(group => {
                const name = group.name || 'Unnamed Group';
                const members = group.members_count || 0;
                const cover = group.cover_image || '/assets/placeholder/image.png';
                const slug = group.slug ? `/group/${group.slug}` : '#';

                return `
                <div class="group-item">
                    <a href="${slug}" class="group-avatar-link">
                        <img src="${cover}" alt="${name}" class="group-avatar">
                    </a>
                    <div class="group-details">
                        <a href="${slug}" class="group-name">${name}</a>
                        <div class="group-info">${members} members</div>
                    </div>
                    <div class="group-actions">
                        <button class="group-btn join" onclick="joinGroup(this, ${group.id})">
                            <i class="bi bi-person-plus"></i> Join
                        </button>
                    </div>
                </div>
            `;
            }).join('');
        } else {
            container.innerHTML = `
                <div class="empty-state">
                    <i class="bi bi-collection"></i>
                    <h6>No group suggestions</h6>
                    <p>Find groups that match your interests</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('Error loading suggested groups:', error);
        const container = document.getElementById('suggestedGroupsList');
        container.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-exclamation-triangle"></i>
                <h6>Error loading groups</h6>
                <p>Please try again later</p>
            </div>
        `;
    }
}

// Load Suggested Events
async function loadSuggestedEvents() {
    try {
        const response = await fetch(base_url+'/webapi/suggested-events', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            }
        });

        if (!response.ok) {
            throw new Error('Failed to load suggested events');
        }

        const data = await response.json();
        const container = document.getElementById('suggestedEventsList');
        
        if (data.success && data.events && data.events.length > 0) {
            container.innerHTML = data.events.map(event => `
                <div class="event-item">
                    <img src="${event.cover_image || '/assets/placeholder/image.png'}" alt="${event.title}" class="event-avatar">
                    <div class="event-details">
                        <div class="event-name">${event.title}</div>
                        <div class="event-info">${formatEventDate(event.start_date)} • ${event.location || 'Online'}</div>
                    </div>
                    <div class="event-actions">
                        <button class="event-btn interest" onclick="showEventInterest(${event.id})">
                            <i class="bi bi-calendar-check"></i> Interest
                        </button>
                    </div>
                </div>
            `).join('');
        } else {
            container.innerHTML = `
                <div class="empty-state">
                    <i class="bi bi-calendar-event"></i>
                    <h6>No event suggestions</h6>
                    <p>Discover exciting events near you</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('Error loading suggested events:', error);
        const container = document.getElementById('suggestedEventsList');
        container.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-exclamation-triangle"></i>
                <h6>Error loading events</h6>
                <p>Please try again later</p>
            </div>
        `;
    }
}

// Helper Functions
function searchHashtag(hashtag) {
    // Redirect to hashtag search or update newsfeed filter
    window.location.href = `/newsfeed?hashtag=${encodeURIComponent(hashtag)}`;
}

function formatEventDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diffTime = date - now;
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays < 0) {
        return 'Past event';
    } else if (diffDays === 0) {
        return 'Today';
    } else if (diffDays === 1) {
        return 'Tomorrow';
    } else if (diffDays < 7) {
        return `In ${diffDays} days`;
    } else {
        return date.toLocaleDateString();
    }
}

// Action Functions
async function likePage(pageId) {
    try {
        const response = await fetch(base_url+'/webapi/page/like-unlike-page', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify({ page_id: pageId })
        });

        if (response.ok) {
            const data = await response.json();
            if (data.success) {
                // Update button state
                const button = event.target.closest('.page-btn');
                if (data.liked) {
                    button.innerHTML = '<i class="bi bi-heart-fill"></i> Liked';
                    button.classList.remove('like');
                    button.classList.add('unlike');
                } else {
                    button.innerHTML = '<i class="bi bi-heart"></i> Like';
                    button.classList.remove('unlike');
                    button.classList.add('like');
                }
            }
        }
    } catch (error) {
        console.error('Error liking page:', error);
    }
}

async function joinGroup(buttonEl, groupId) {
    try {
        const button = buttonEl.closest('.group-btn');
        button.disabled = true;

        const response = await fetch(base_url+'/webapi/group/join', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify({ group_id: groupId })
        });

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

        const data = await response.json();
        if (data.status === 200 || data.success) {
            button.innerHTML = '<i class="bi bi-check"></i> Joined';
            button.classList.remove('join');
            button.classList.add('leave');
            button.onclick = () => leaveGroup(button, groupId);
        }
    } catch (error) {
        console.error('Error joining group:', error);
    } finally {
        const button = buttonEl.closest('.group-btn');
        if (button) {
            button.disabled = false;
        }
    }
}

async function leaveGroup(buttonEl, groupId) {
    try {
        const button = buttonEl.closest('.group-btn');
        button.disabled = true;

        const response = await fetch(base_url+'/webapi/group/leave', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify({ group_id: groupId })
        });

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

        const data = await response.json();
        if (data.status === 200 || data.success) {
            button.innerHTML = '<i class="bi bi-person-plus"></i> Join';
            button.classList.remove('leave');
            button.classList.add('join');
            button.onclick = () => joinGroup(button, groupId);
        }
    } catch (error) {
        console.error('Error leaving group:', error);
    } finally {
        const button = buttonEl.closest('.group-btn');
        if (button) {
            button.disabled = false;
        }
    }
}

function showEventInterest(eventId) {
    // Show modal or redirect to event detail page
    window.location.href = `/events/detail/${eventId}`;
}

// Initialize all widgets when page loads
document.addEventListener('DOMContentLoaded', function() {
    // Load all widgets
    loadTrendingHashtags();
    loadSuggestedUsers();
    loadSuggestedPages();
    loadSuggestedGroups();
    loadSuggestedEvents();
    
    // Set up auto-refresh every 5 minutes
    setInterval(() => {
        loadTrendingHashtags();
    }, 300000); // 5 minutes
});

function linkifyHashtags(text) {
    return text.replace(/#(\w+)/g, `<a href="${base_url}/hashtag/$1" class="hashtag">#$1</a>`);
}

function decodeHTMLEntities(text) {
    var textarea = document.createElement("textarea");
    textarea.innerHTML = text;
    return textarea.value;
}

function processPost(postHtml) {
    // Create a temporary DOM element
    let tempDiv = document.createElement("div");
    tempDiv.innerHTML = decodeHTMLEntities(postHtml);

    // Extract attributes from original <div>
    let originalDiv = tempDiv.querySelector("div");
    let attrs = originalDiv.getAttributeNames().map(attr => `${attr}="${originalDiv.getAttribute(attr)}"`).join(" ");

    // Extract inner text
    let innerText = originalDiv.innerText;

    // Run hashtag function
    let updatedText = linkifyHashtags(innerText);

    // Rebuild the div with attributes + processed text
    return `<div ${attrs}>${updatedText}</div>`;
}

function truncateMiddle(text, maxLength) {
    if (text.length <= maxLength) return text;

    const extIndex = text.lastIndexOf(".");
    let ext = "";
    if (extIndex !== -1) {
        ext = text.substring(extIndex); // keep file extension
        text = text.substring(0, extIndex);
    }

    const charsToShow = maxLength - ext.length - 5; // 5 dots in middle
    const front = Math.ceil(charsToShow / 2);
    const back = Math.floor(charsToShow / 2);

    return text.substring(0, front) + "....." + text.substring(text.length - back) + ext;
}
