// Improved JavaScript (friends.js)

// Global state management
const state = {
    currentOffset: 0,
    loading: false,
    filter: 'all',
    sortBy: 'recent',
    allLoaded: false,
    itemsPerPage: 12,
    hasMore: true
};

$(document).ready(function () {
    // Initialize tooltips and popovers
    $('[data-bs-toggle="tooltip"]').tooltip();
    $('[data-bs-toggle="popover"]').popover();

 
    // Debounced search implementation
    let searchTimeout;
    $("#search-input").on("input", function() {
        clearTimeout(searchTimeout);
        const $searchIndicator = $("#search-indicator");
        $searchIndicator.show();
        
        searchTimeout = setTimeout(() => {
            get_all_friends();
            $searchIndicator.hide();
        }, 500);
    });

    // Filter handling
    $(".friend-filter").on("click", function() {
        $(".friend-filter").removeClass("active");
        $(this).addClass("active");
        state.filter = $(this).data("filter");
        get_all_friends();
    });

    // Sort handling
    $("#sort-select").on("change", function() {
        state.sortBy = $(this).val();
        get_all_friends();
    });
});

// Enhanced friend card render with more features
function renderFriendCard(friend) {
    const isOnline = friend.last_active ? (new Date() - new Date(friend.last_active)) < 300000 : false;
    const mutualCount = friend.mutual_friends_count || 0;
    
    return `
        <div class="col-md-4 friend-card-wrapper" data-friend-id="${friend.id}">
            <div class="card h-100 border-0 shadow-sm hover-shadow-lg transition-all duration-300 rounded-3 friend-card">
                <div class="position-relative">
                    <div class="friend-cover-wrapper">
                        <img src="${friend.cover || 'assets/placeholder/cover.png'}" 
                             class="card-img-top rounded-top-3" 
                             alt="Cover Photo" 
                             style="height: 120px; object-fit: cover;">
                        ${isOnline ? '<span class="position-absolute top-0 start-0 m-2 badge bg-success">Online</span>' : ''}
                    </div>
                    <div class="position-absolute start-50 translate-middle-x profile-image-wrapper" style="bottom: -45px;">
                        <img src="${friend.avatar || 'assets/images/avatar/default-avatar.jpg'}" 
                             class="rounded-circle border-4 border-white shadow" 
                             width="90" height="90" 
                             alt="${friend.first_name}'s Profile Photo">
                    </div>
                    <div class="friend-actions position-absolute top-0 end-0 m-2">
                        <div class="dropdown">
                            <button class="btn btn-light btn-sm rounded-circle shadow-sm" data-bs-toggle="dropdown">
                                <i class="fas fa-ellipsis-h"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                                
                                <li><a class="dropdown-item" href="#" onclick="viewFriendProfile(${friend.id})">
                                    <i class="fas fa-user me-2"></i>View Profile</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item text-danger" href="#" onclick="unfriend(${friend.id})">
                                    <i class="fas fa-user-times me-2"></i>Unfriend</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="card-body text-center pt-5 mt-5">
                    <h6 class="card-title mb-1">
                        <a href="#" class="text-decoration-none stretched-link">${friend.first_name} ${friend.last_name}</a>
                    </h6>
                    <p class="text-muted small mb-2">@${friend.username}</p>
                    <div class="d-flex justify-content-center gap-2 mb-3">
                        ${mutualCount > 0 ? `
                            <span class="badge bg-light text-dark" data-bs-toggle="tooltip" 
                                  title="${mutualCount} mutual friends">
                                <i class="fas fa-users me-1"></i>${mutualCount} mutual
                            </span>
                        ` : ''}
                        ${friend.location ? `
                            <span class="badge bg-light text-dark">
                                <i class="fas fa-map-marker-alt me-1"></i>${friend.location}
                            </span>
                        ` : ''}
                    </div>
                </div>
                <div class="card-footer bg-transparent border-0 pt-0">
                    <div class="d-grid gap-2">
                        <button class="btn btn-primary btn-sm" onclick="startChat(${friend.id})">
                            <i class="fas fa-comment me-2"></i>Message
                        </button>
                        <button class="btn btn-light btn-sm friend-role-btn" 
                                data-friend-id="${friend.id}" 
                                data-current-role="${friend.role || 'Friend'}">
                            <i class="fas fa-star me-2"></i>
                            <span class="role-text">${friend.role || 'Friend'}</span>
                            <i class="fas fa-chevron-down ms-2"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
}

// Enhanced get all friends with loading state and error handling
function get_all_friends() {
    if (state.loading) return;
    
    // Reset offset when loading fresh data (search/filter change)
    state.currentOffset = 0;
    state.allLoaded = false;
    
    state.loading = true;
    $("#friends-container").addClass("loading-opacity");
    $("#loading-indicator").show();

    const params = {
        limit: state.itemsPerPage,
        offset: state.currentOffset,
        keyword: $("#search-input").val() || '',
        filter: state.filter,
        sort: state.sortBy
    };

    axios.get(`${base_url}/webapi/friends/get-all`, { params })
        .then(response => {
            if (response.data.status === 200) {
                let friends = response.data.data;
                let pagination = response.data.pagination;
                let html = "";

                if (friends.length === 0) {
                    html = createEmptyState();
                    $("#load-more-friends").hide();
                } else {
                    friends.forEach(friend => {
                        html += renderFriendCard(friend);
                    });
                    
                    // Update state based on pagination info
                    state.hasMore = pagination.has_more;
                    state.allLoaded = !pagination.has_more;
                    
                    // Show or hide load more button
                    if (pagination.has_more) {
                        $("#load-more-friends").show();
                    } else {
                        $("#load-more-friends").hide();
                    }
                }

                $("#friends-container").html(html);
                initializeCardInteractions();
            } else {
                showError("Failed to load friends");
            }
        })
        .catch(error => {
            showError("Failed to load friends");
            console.error("API request failed:", error);
        })
        .finally(() => {
            state.loading = false;
            $("#friends-container").removeClass("loading-opacity");
            $("#loading-indicator").hide();
        });
}

// Empty state template
function createEmptyState() {
    return `
        <div class="col-12 text-center py-5">
            <div class="empty-state">
                <i class="fas fa-users fa-3x text-muted mb-3"></i>
                <h5>No Friends Found</h5>
                <p class="text-muted">Try adjusting your search or filters</p>
                <button class="btn btn-primary" onclick="resetFilters()">
                    <i class="fas fa-sync-alt me-2"></i>Reset Filters
                </button>
            </div>
        </div>
    `;
}

// Error handling function
function showError(message) {
    const errorHtml = `
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    $("#error-container").html(errorHtml);
}

// Initialize card interactions
function initializeCardInteractions() {
    // Role selection dropdown
    $(".friend-role-btn").on("click", function(e) {
        e.preventDefault();
        const friendId = $(this).data("friend-id");
        const currentRole = $(this).data("current-role");
        
        const $roleMenu = $(`
            <div class="role-selection-menu">
                <div class="list-group">
                    <button class="list-group-item" data-role="Friend">
                        <i class="fas fa-user me-2"></i>Friend
                    </button>
                    <button class="list-group-item" data-role="Close Friend">
                        <i class="fas fa-star me-2"></i>Close Friend
                    </button>
                    <button class="list-group-item" data-role="Family">
                        <i class="fas fa-home me-2"></i>Family
                    </button>
                </div>
            </div>
        `);

        // Position the menu
        const buttonPos = $(this).offset();
        $roleMenu.css({
            position: 'absolute',
            top: buttonPos.top + $(this).outerHeight(),
            left: buttonPos.left
        });

        // Handle role selection
        $roleMenu.find(".list-group-item").on("click", function() {
            const newRole = $(this).data("role");
            changeFriendRole(friendId, newRole);
            $roleMenu.remove();
        });

        // Add to body and handle outside clicks
        $("body").append($roleMenu);
        $(document).one("click", function() {
            $roleMenu.remove();
        });
    });
}

// Add loading state to stats
function getFriendStats() {
    $("#stats-container .card").addClass("loading-opacity");
    
    axios.get(`${base_url}/webapi/friends/stats`)
        .then(response => {
            if (response.data.status === 200) {
                const stats = response.data.data;
                Object.keys(stats).forEach(key => {
                    $(`#${key.replace('_', '-')}`).text(stats[key]);
                });
            }
        })
        .catch(error => {
            console.error("Error fetching stats:", error);
        })
        .finally(() => {
            $("#stats-container .card").removeClass("loading-opacity");
        });
}

// Additional state management


// Enhanced friend role management
function changeFriendRole(friendId, newRole) {
    const $roleBtn = $(`.friend-role-btn[data-friend-id="${friendId}"]`);
    const $roleText = $roleBtn.find('.role-text');
    const oldRole = $roleBtn.data('current-role');

    // Optimistic UI update
    $roleText.html(`<i class="fas fa-spinner fa-spin me-2"></i>${newRole}`);
    
    axios.post(`${base_url}/webapi/friends/change-role`, {
        friend_id: friendId,
        role: newRole
    })
    .then(response => {
        if (response.data.status === 200) {
            $roleBtn.data('current-role', newRole);
            $roleText.html(newRole);
            
            // Show success toast
            showToast('success', `Friend role updated to ${newRole}`);
            
            // Update UI elements
            updateRoleIndicators(friendId, newRole);
        } else {
            // Revert on failure
            $roleText.html(oldRole);
            showToast('error', 'Failed to update friend role');
        }
    })
    .catch(error => {
        console.error("Error changing friend role:", error);
        $roleText.html(oldRole);
        showToast('error', 'Failed to update friend role');
    });
}

// Enhanced friend list management
function createFriendList() {
    const formData = new FormData(document.getElementById('createListForm'));
    const listData = Object.fromEntries(formData.entries());

    axios.post(`${base_url}/webapi/friends/create-list`, listData)
        .then(response => {
            if (response.data.status === 200) {
                $('#createListModal').modal('hide');
                showToast('success', 'Friend list created successfully');
                loadFriendLists();
            } else {
                showToast('error', 'Failed to create friend list');
            }
        })
        .catch(error => {
            console.error("Error creating friend list:", error);
            showToast('error', 'Failed to create friend list');
        });
}

function loadFriendLists() {
    axios.get(`${base_url}/webapi/friends/get-all`)
        .then(response => {
            if (response.data.status === 200) {
                const lists = response.data.data;
                let html = '';
                
                lists.forEach(list => {
                    html += renderFriendList(list);
                });
                
                $("#friend-lists-container").html(html);
            }
        })
        .catch(error => {
            console.error("Error loading friend lists:", error);
        });
}

function renderFriendList(list) {
    return `
        <div class="col-md-6">
            <div class="card border hover-shadow-lg transition-all">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="icon-lg bg-${list.icon_color || 'primary'} bg-opacity-10 rounded-circle text-${list.icon_color || 'primary'} me-3">
                            <i class="fas fa-${list.icon || 'users'}"></i>
                        </div>
                        <div class="flex-grow-1">
                            <h6 class="mb-1">${list.name}</h6>
                            <p class="text-muted small mb-0">
                                ${list.member_count} members · ${list.privacy}
                            </p>
                        </div>
                        <div class="dropdown">
                            <button class="btn btn-light btn-sm" data-bs-toggle="dropdown">
                                <i class="fas fa-ellipsis-v"></i>
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="#" onclick="viewFriendList(${list.id})">
                                    <i class="fas fa-eye me-2"></i>View Members</a></li>
                                <li><a class="dropdown-item" href="#" onclick="editFriendList(${list.id})">
                                    <i class="fas fa-edit me-2"></i>Edit List</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item text-danger" href="#" onclick="deleteFriendList(${list.id})">
                                    <i class="fas fa-trash me-2"></i>Delete List</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
}

// Friend management functions
function unfriend(friendId) {
    Swal.fire({
        title: 'Unfriend Confirmation',
        text: 'Are you sure you want to remove this friend?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        confirmButtonText: 'Yes, unfriend',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            axios.post(`${base_url}/webapi/friends/unfriend`, { friend_id: friendId })
                .then(response => {
                    if (response.data.status === 200) {
                        $(`.friend-card-wrapper[data-friend-id="${friendId}"]`).fadeOut(300, function() {
                            $(this).remove();
                            showToast('success', 'Friend removed successfully');
                            getFriendStats(); // Update stats
                        });
                    } else {
                        showToast('error', 'Failed to remove friend');
                    }
                })
                .catch(error => {
                    console.error("Error unfriending:", error);
                    showToast('error', 'Failed to remove friend');
                });
        }
    });
}

// Chat functionality
function startChat(friendId) {
    // Update last interaction
    axios.post(`${base_url}/webapi/friends/last-interaction`, { 
        friend_id: friendId,
        type: 'message'
    });
    
    // Open chat window/redirect to chat
    window.location.href = `${base_url}/messages/chat/${friendId}`;
}

// Enhanced infinite scroll functionality
function loadMoreFriends() {
    if (state.loading || state.allLoaded) return;
    
    state.loading = true;
    
    // Increment offset by the number of items per page
    state.currentOffset += state.itemsPerPage;
    
    const params = {
        limit: state.itemsPerPage,
        offset: state.currentOffset,
        keyword: $("#search-input").val() || '',
        filter: state.filter,
        sort: state.sortBy
    };
    
    $("#load-more-friends").prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-2"></i>Loading...');
    
    axios.get(`${base_url}/webapi/friends/get-all`, { params })
        .then(response => {
            if (response.data.status === 200) {
                const friends = response.data.data;
                const pagination = response.data.pagination;
                
                let html = '';
                friends.forEach(friend => {
                    html += renderFriendCard(friend);
                });
                
                $("#friends-container").append(html);
                initializeCardInteractions();
                
                // Update state based on pagination
                state.hasMore = pagination.has_more;
                state.allLoaded = !pagination.has_more;
                
                // Hide button if no more friends
                if (!pagination.has_more) {
                    $("#load-more-friends").hide();
                } else {
                    $("#load-more-friends").show();
                }
            }
        })
        .catch(error => {
            console.error("Error loading more friends:", error);
            showToast('error', 'Failed to load more friends');
            // Revert offset on error
            state.currentOffset -= state.itemsPerPage;
        })
        .finally(() => {
            state.loading = false;
            $("#load-more-friends").prop('disabled', false).html('<i class="fas fa-sync-alt me-2"></i>Load More');
        });
}

// Utility functions
function showToast(type, message) {
    const bgClass = type === 'success' ? 'bg-success' : 'bg-danger';
    const toast = `
        <div class="toast ${bgClass} text-white" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-body">
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>
                ${message}
            </div>
        </div>
    `;
    
    const $toast = $(toast);
    $("#toast-container").append($toast);
    $toast.toast('show');
    
    $toast.on('hidden.bs.toast', function() {
        $(this).remove();
    });
}

// Add these to your blade file
function addToastContainer() {
    $('body').append(`
        <div id="toast-container" class="position-fixed bottom-0 end-0 p-3" style="z-index: 1050;">
        </div>
    `);
}

// Initialize everything
$(document).ready(function() {
    addToastContainer();
    
    // Initialize tooltips and popovers
    $('[data-bs-toggle="tooltip"]').tooltip();
    $('[data-bs-toggle="popover"]').popover();
    
    // Initialize components
    get_all_friends();
    getFriendStats();
    loadFriendLists();
    
    // Initialize infinite scroll
    $(window).scroll(function() {
        if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
            loadMoreFriends();
        }
    });
});