<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout}">

<head>
    <title>Activity Details</title>
</head>

<body>
    <div layout:fragment="content">
        <!-- Loading Indicator -->
        <div id="loadingIndicator" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2 text-muted">Loading activity...</p>
        </div>

        <!-- Error Alert -->
        <div id="errorAlert" class="alert alert-danger d-none" role="alert">
            <i class="bi bi-exclamation-triangle-fill"></i>
            <span id="errorMessage"></span>
        </div>

        <!-- Activity Content -->
        <div id="activityContent" class="d-none">
            <!-- Activity Header -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h2 id="activityTitle">Activity Title</h2>
                            <p class="text-muted mb-2">
                                <span id="activityType" class="activity-type-badge"></span>
                                <span class="ms-2">
                                    <i class="bi bi-calendar"></i>
                                    <span id="activityDate"></span>
                                </span>
                                <span class="ms-2" id="visibilityBadge">
                                    <i class="bi bi-globe"></i>
                                    <span id="activityVisibility"></span>
                                </span>
                            </p>
                            <p id="activityDescription" class="text-muted"></p>
                        </div>
                        <div class="btn-group" role="group" id="activityActions" style="display: none;">
                            <a href="#" id="editBtn" class="btn btn-outline-primary">
                                <i class="bi bi-pencil"></i> Edit
                            </a>
                            <button id="deleteBtn" class="btn btn-outline-danger">
                                <i class="bi bi-trash"></i> Delete
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Activity Metrics -->
            <div class="mb-3">
                <table class="table table-sm table-borderless mb-0">
                    <tbody>
                        <tr>
                            <td class="text-muted" style="width: 25%;">Distance</td>
                            <td class="fw-bold" id="metricDistance">--</td>
                            <td class="text-muted" style="width: 25%;">Duration</td>
                            <td class="fw-bold" id="metricDuration">--</td>
                        </tr>
                        <tr>
                            <td class="text-muted">Elevation</td>
                            <td class="fw-bold" id="metricElevation">--</td>
                            <td class="text-muted">Avg Pace</td>
                            <td class="fw-bold" id="metricPace">--</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Map -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-map"></i> Route Map
                            </h5>
                        </div>
                        <div class="card-body p-0">
                            <div id="activityMap" class="map-container-large"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Elevation Chart -->
            <div class="row mb-4" id="elevationSection" style="display: none;">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-graph-up"></i> Elevation Profile
                            </h5>
                        </div>
                        <div class="card-body">
                            <canvas id="elevationChart" height="100"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Additional Metrics -->
            <div class="row mb-4" id="additionalMetrics" style="display: none;">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-speedometer2"></i> Additional Metrics
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4 mb-3" id="avgHeartRateContainer" style="display: none;">
                                    <strong>Average Heart Rate:</strong>
                                    <span id="avgHeartRate" class="float-end">-- bpm</span>
                                </div>
                                <div class="col-md-4 mb-3" id="maxHeartRateContainer" style="display: none;">
                                    <strong>Max Heart Rate:</strong>
                                    <span id="maxHeartRate" class="float-end">-- bpm</span>
                                </div>
                                <div class="col-md-4 mb-3" id="avgCadenceContainer" style="display: none;">
                                    <strong>Average Cadence:</strong>
                                    <span id="avgCadence" class="float-end">-- rpm</span>
                                </div>
                                <div class="col-md-4 mb-3" id="avgSpeedContainer" style="display: none;">
                                    <strong>Average Speed:</strong>
                                    <span id="avgSpeed" class="float-end">-- km/h</span>
                                </div>
                                <div class="col-md-4 mb-3" id="maxSpeedContainer" style="display: none;">
                                    <strong>Max Speed:</strong>
                                    <span id="maxSpeed" class="float-end">-- km/h</span>
                                </div>
                                <div class="col-md-4 mb-3" id="caloriesContainer" style="display: none;">
                                    <strong>Calories:</strong>
                                    <span id="calories" class="float-end">-- kcal</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Social Interactions -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">
                                <i class="bi bi-chat-heart"></i> Social
                            </h5>
                            <div>
                                <button id="likeBtn" class="btn btn-sm btn-outline-danger me-2">
                                    <i class="bi bi-heart"></i>
                                    <span id="likeBtnText">Like</span>
                                    (<span id="likeCount">0</span>)
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <!-- Likes Section -->
                            <div class="mb-4" id="likesSection">
                                <h6 class="text-muted mb-3">
                                    <i class="bi bi-heart-fill text-danger"></i>
                                    Liked by <span id="likesCountText">0</span>
                                </h6>
                                <div id="likesList" class="d-flex flex-wrap gap-2">
                                    <!-- Likes will be populated here -->
                                </div>
                            </div>

                            <!-- Comments Section -->
                            <div>
                                <h6 class="text-muted mb-3">
                                    <i class="bi bi-chat-left-text"></i>
                                    Comments (<span id="commentsCount">0</span>)
                                </h6>

                                <!-- Comment Form -->
                                <div id="commentForm" class="mb-4" style="display: none;">
                                    <form id="addCommentForm">
                                        <div class="mb-3">
                                            <textarea
                                                id="commentContent"
                                                class="form-control"
                                                rows="3"
                                                placeholder="Write a comment..."
                                                required
                                            ></textarea>
                                        </div>
                                        <button type="submit" class="btn btn-primary btn-sm">
                                            <i class="bi bi-send"></i> Post Comment
                                        </button>
                                    </form>
                                </div>

                                <!-- Comments List -->
                                <div id="commentsList">
                                    <!-- Comments will be populated here -->
                                </div>

                                <!-- Login prompt for non-authenticated users -->
                                <div id="loginPrompt" style="display: none;">
                                    <p class="text-muted">
                                        <a href="/login">Log in</a> to like or comment on this activity.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Back Button -->
            <div class="row">
                <div class="col-12">
                    <a th:href="@{/activities}" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-left"></i> Back to Activities
                    </a>
                </div>
            </div>
        </div>

        <!-- Delete Confirmation Modal -->
        <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="deleteModalLabel">
                            <i class="bi bi-exclamation-triangle text-danger"></i>
                            Delete Activity
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <p>Are you sure you want to delete this activity?</p>
                        <p class="text-danger mb-0"><strong>This action cannot be undone.</strong></p>
                    </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="confirmDeleteBtn">
                            <i class="bi bi-trash"></i> Delete
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Custom Scripts -->
    <th:block layout:fragment="scripts">
        <script th:inline="javascript">
            document.addEventListener('DOMContentLoaded', function() {
                const activityId = window.location.pathname.split('/').pop();
                const loadingIndicator = document.getElementById('loadingIndicator');
                const errorAlert = document.getElementById('errorAlert');
                const errorMessage = document.getElementById('errorMessage');
                const activityContent = document.getElementById('activityContent');

                // Load activity details
                loadActivity();

                async function loadActivity() {
                    try {
                        // Use authenticated fetch if user is logged in, otherwise regular fetch
                        // This allows public activities to be viewed without authentication
                        const response = FitPubAuth.isAuthenticated()
                            ? await FitPubAuth.authenticatedFetch(`/api/activities/${activityId}`)
                            : await fetch(`/api/activities/${activityId}`);

                        if (response.ok) {
                            const activity = await response.json();
                            renderActivity(activity);

                            // Hide loading, show content
                            loadingIndicator.classList.add('d-none');
                            activityContent.classList.remove('d-none');
                        } else {
                            throw new Error('Failed to load activity');
                        }
                    } catch (error) {
                        console.error('Error loading activity:', error);
                        loadingIndicator.classList.add('d-none');
                        errorMessage.textContent = 'Failed to load activity. Please try again.';
                        errorAlert.classList.remove('d-none');
                    }
                }

                function renderActivity(activity) {
                    // Header
                    document.getElementById('activityTitle').textContent = activity.title || 'Untitled Activity';
                    document.getElementById('activityType').textContent = activity.activityType;
                    document.getElementById('activityType').className = `activity-type-badge activity-type-${activity.activityType.toLowerCase()}`;
                    document.getElementById('activityDate').textContent = new Date(activity.startedAt).toLocaleString();
                    document.getElementById('activityVisibility').textContent = activity.visibility;

                    // Visibility icon
                    const visIcon = getVisibilityIcon(activity.visibility);
                    document.querySelector('#visibilityBadge i').className = `bi bi-${visIcon}`;
                    document.getElementById('visibilityBadge').className = `ms-2 visibility-${activity.visibility.toLowerCase()}`;

                    // Description
                    if (activity.description) {
                        document.getElementById('activityDescription').textContent = activity.description;
                    } else {
                        document.getElementById('activityDescription').style.display = 'none';
                    }

                    // Show Edit/Delete buttons only if user is logged in and owns the activity
                    if (FitPubAuth.isAuthenticated()) {
                        // Fetch current user to check if they own this activity
                        checkActivityOwnership(activity);
                    }

                    // Metrics
                    document.getElementById('metricDistance').textContent = formatDistance(activity.totalDistance);
                    document.getElementById('metricDuration').textContent = formatDuration(activity.totalDuration);
                    document.getElementById('metricElevation').textContent = activity.elevationGain ? Math.round(activity.elevationGain) + 'm' : 'N/A';

                    // Calculate pace
                    if (activity.totalDistance && activity.totalDuration) {
                        const paceSeconds = activity.totalDuration / (activity.totalDistance / 1000);
                        document.getElementById('metricPace').textContent = formatPace(paceSeconds);
                    }

                    // Render map if track data exists
                    if (activity.simplifiedTrack) {
                        renderMap(activity.simplifiedTrack);
                    }

                    // Render elevation chart if data exists
                    if (activity.trackPoints && activity.trackPoints.length > 0) {
                        const hasElevation = activity.trackPoints.some(p => p.elevation != null);
                        if (hasElevation) {
                            document.getElementById('elevationSection').style.display = 'block';
                            renderElevationChart(activity.trackPoints);
                        }
                    }

                    // Additional metrics
                    renderAdditionalMetrics(activity);

                    // Load social interactions
                    loadLikes();
                    loadComments();
                    setupSocialInteractions(activity);
                }

                /**
                 * Check if the current user owns this activity and show edit/delete buttons if so.
                 */
                async function checkActivityOwnership(activity) {
                    try {
                        const response = await FitPubAuth.authenticatedFetch('/api/users/me');
                        if (response.ok) {
                            const currentUser = await response.json();
                            if (currentUser.id === activity.userId) {
                                document.getElementById('activityActions').style.display = 'block';
                                document.getElementById('editBtn').href = `/activities/${activity.id}/edit`;
                            }
                        }
                    } catch (error) {
                        console.error('Error checking activity ownership:', error);
                        // Don't show buttons if there's an error
                    }
                }

                function renderMap(simplifiedTrack) {
                    // Parse GeoJSON from simplifiedTrack
                    const geoJson = {
                        type: 'LineString',
                        coordinates: simplifiedTrack.coordinates
                    };

                    // Create map (needs to be done after container is visible)
                    setTimeout(() => {
                        const map = FitPub.createActivityMap('activityMap', geoJson, {
                            showStartEnd: false,  // Privacy: Do not show start/end markers
                            fitBounds: true
                        });

                        // Force fit bounds again after map is fully rendered
                        if (map && map.trackLayer) {
                            setTimeout(() => {
                                try {
                                    const bounds = map.trackLayer.getBounds();
                                    if (bounds.isValid()) {
                                        map.fitBounds(bounds, { padding: [50, 50] });
                                    }
                                } catch (e) {
                                    console.warn('Could not fit bounds on second attempt:', e);
                                }
                            }, 200);
                        }
                    }, 50);
                }

                function renderElevationChart(trackPoints) {
                    // Calculate cumulative distance and prepare elevation data
                    let cumulativeDistance = 0;
                    const elevationData = [];

                    for (let i = 0; i < trackPoints.length; i++) {
                        const point = trackPoints[i];

                        // Calculate distance from previous point (simple Haversine approximation)
                        if (i > 0 && point.latitude && point.longitude) {
                            const prev = trackPoints[i - 1];
                            if (prev.latitude && prev.longitude) {
                                const distance = calculateDistance(
                                    prev.latitude, prev.longitude,
                                    point.latitude, point.longitude
                                );
                                cumulativeDistance += distance;
                            }
                        }

                        // Add point if it has elevation data
                        if (point.elevation != null) {
                            elevationData.push({
                                distance: cumulativeDistance,
                                elevation: point.elevation
                            });
                        }
                    }

                    if (elevationData.length > 0) {
                        // Smooth elevation data to remove zero/invalid values
                        const smoothedData = smoothElevationData(elevationData);
                        FitPub.createElevationChart('elevationChart', smoothedData);
                    }
                }

                /**
                 * Smooth elevation data by interpolating zero/invalid values and applying moving average
                 * @param {Array} data - Array of {distance, elevation} objects
                 * @returns {Array} Smoothed elevation data
                 */
                function smoothElevationData(data) {
                    if (data.length === 0) return data;

                    // Step 1: Replace zeros and invalid values with interpolated values
                    const interpolated = [...data];

                    for (let i = 0; i < interpolated.length; i++) {
                        if (interpolated[i].elevation === 0 || interpolated[i].elevation == null) {
                            // Find previous valid value
                            let prevIndex = i - 1;
                            while (prevIndex >= 0 && (interpolated[prevIndex].elevation === 0 || interpolated[prevIndex].elevation == null)) {
                                prevIndex--;
                            }

                            // Find next valid value
                            let nextIndex = i + 1;
                            while (nextIndex < interpolated.length && (interpolated[nextIndex].elevation === 0 || interpolated[nextIndex].elevation == null)) {
                                nextIndex++;
                            }

                            // Interpolate between valid values
                            if (prevIndex >= 0 && nextIndex < interpolated.length) {
                                const prevElevation = interpolated[prevIndex].elevation;
                                const nextElevation = interpolated[nextIndex].elevation;
                                const ratio = (i - prevIndex) / (nextIndex - prevIndex);
                                interpolated[i].elevation = prevElevation + (nextElevation - prevElevation) * ratio;
                            } else if (prevIndex >= 0) {
                                // Use previous value if no next value available
                                interpolated[i].elevation = interpolated[prevIndex].elevation;
                            } else if (nextIndex < interpolated.length) {
                                // Use next value if no previous value available
                                interpolated[i].elevation = interpolated[nextIndex].elevation;
                            }
                        }
                    }

                    // Step 2: Apply moving average smoothing (window size 5)
                    const windowSize = 5;
                    const smoothed = [];

                    for (let i = 0; i < interpolated.length; i++) {
                        const start = Math.max(0, i - Math.floor(windowSize / 2));
                        const end = Math.min(interpolated.length, i + Math.ceil(windowSize / 2));

                        let sum = 0;
                        let count = 0;

                        for (let j = start; j < end; j++) {
                            if (interpolated[j].elevation != null && interpolated[j].elevation !== 0) {
                                sum += interpolated[j].elevation;
                                count++;
                            }
                        }

                        smoothed.push({
                            distance: interpolated[i].distance,
                            elevation: count > 0 ? sum / count : interpolated[i].elevation
                        });
                    }

                    return smoothed;
                }

                // Haversine formula to calculate distance between two GPS points
                function calculateDistance(lat1, lon1, lat2, lon2) {
                    const R = 6371000; // Earth's radius in meters
                    const dLat = (lat2 - lat1) * Math.PI / 180;
                    const dLon = (lon2 - lon1) * Math.PI / 180;
                    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                              Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                              Math.sin(dLon / 2) * Math.sin(dLon / 2);
                    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
                    return R * c;
                }

                function renderAdditionalMetrics(activity) {
                    let hasAdditionalMetrics = false;

                    // Average Heart Rate
                    if (activity.averageHeartRate) {
                        document.getElementById('avgHeartRate').textContent = Math.round(activity.averageHeartRate) + ' bpm';
                        document.getElementById('avgHeartRateContainer').style.display = 'block';
                        hasAdditionalMetrics = true;
                    }

                    // Max Heart Rate
                    if (activity.maxHeartRate) {
                        document.getElementById('maxHeartRate').textContent = Math.round(activity.maxHeartRate) + ' bpm';
                        document.getElementById('maxHeartRateContainer').style.display = 'block';
                        hasAdditionalMetrics = true;
                    }

                    // Average Cadence
                    if (activity.averageCadence) {
                        document.getElementById('avgCadence').textContent = Math.round(activity.averageCadence) + ' rpm';
                        document.getElementById('avgCadenceContainer').style.display = 'block';
                        hasAdditionalMetrics = true;
                    }

                    // Average Speed
                    if (activity.averageSpeed) {
                        document.getElementById('avgSpeed').textContent = (activity.averageSpeed * 3.6).toFixed(1) + ' km/h';
                        document.getElementById('avgSpeedContainer').style.display = 'block';
                        hasAdditionalMetrics = true;
                    }

                    // Max Speed
                    if (activity.maxSpeed) {
                        document.getElementById('maxSpeed').textContent = (activity.maxSpeed * 3.6).toFixed(1) + ' km/h';
                        document.getElementById('maxSpeedContainer').style.display = 'block';
                        hasAdditionalMetrics = true;
                    }

                    // Calories
                    if (activity.calories) {
                        document.getElementById('calories').textContent = Math.round(activity.calories) + ' kcal';
                        document.getElementById('caloriesContainer').style.display = 'block';
                        hasAdditionalMetrics = true;
                    }

                    if (hasAdditionalMetrics) {
                        document.getElementById('additionalMetrics').style.display = 'block';
                    }
                }

                // Social interactions functionality
                async function loadLikes() {
                    try {
                        const response = await fetch(`/api/activities/${activityId}/likes`);
                        if (response.ok) {
                            const likes = await response.json();
                            renderLikes(likes);
                        }
                    } catch (error) {
                        console.error('Error loading likes:', error);
                    }
                }

                function renderLikes(likes) {
                    const likesList = document.getElementById('likesList');
                    const likeCount = document.getElementById('likeCount');
                    const likesCountText = document.getElementById('likesCountText');

                    likeCount.textContent = likes.length;
                    likesCountText.textContent = likes.length;

                    if (likes.length === 0) {
                        likesList.innerHTML = '<span class="text-muted">No likes yet</span>';
                        return;
                    }

                    likesList.innerHTML = likes.map(like => {
                        const displayName = like.displayName || like.username || 'Unknown';
                        const avatarHtml = like.avatarUrl
                            ? `<img src="${like.avatarUrl}" alt="${displayName}" class="rounded-circle me-2" width="32" height="32">`
                            : `<i class="bi bi-person-circle me-2" style="font-size: 32px;"></i>`;

                        return `
                            <div class="d-flex align-items-center p-2 border rounded">
                                ${avatarHtml}
                                <span>${displayName}</span>
                            </div>
                        `;
                    }).join('');
                }

                async function loadComments() {
                    try {
                        const response = await fetch(`/api/activities/${activityId}/comments`);
                        if (response.ok) {
                            const commentsPage = await response.json();
                            renderComments(commentsPage.content || []);
                        }
                    } catch (error) {
                        console.error('Error loading comments:', error);
                    }
                }

                function renderComments(comments) {
                    const commentsList = document.getElementById('commentsList');
                    const commentsCount = document.getElementById('commentsCount');

                    commentsCount.textContent = comments.length;

                    if (comments.length === 0) {
                        commentsList.innerHTML = '<p class="text-muted">No comments yet. Be the first to comment!</p>';
                        return;
                    }

                    commentsList.innerHTML = comments.map(comment => {
                        const displayName = comment.displayName || comment.username || 'Unknown';
                        const avatarHtml = comment.avatarUrl
                            ? `<img src="${comment.avatarUrl}" alt="${displayName}" class="rounded-circle" width="40" height="40">`
                            : `<i class="bi bi-person-circle" style="font-size: 40px;"></i>`;

                        const createdAt = new Date(comment.createdAt).toLocaleString();
                        const deleteBtn = comment.canDelete
                            ? `<button class="btn btn-sm btn-outline-danger delete-comment-btn" data-comment-id="${comment.id}">
                                <i class="bi bi-trash"></i>
                               </button>`
                            : '';

                        return `
                            <div class="d-flex mb-3 pb-3 border-bottom" data-comment-id="${comment.id}">
                                <div class="me-3">
                                    ${avatarHtml}
                                </div>
                                <div class="flex-grow-1">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <strong>${displayName}</strong>
                                            <small class="text-muted ms-2">${createdAt}</small>
                                        </div>
                                        ${deleteBtn}
                                    </div>
                                    <p class="mb-0 mt-1">${escapeHtml(comment.content)}</p>
                                </div>
                            </div>
                        `;
                    }).join('');

                    // Add delete event listeners
                    document.querySelectorAll('.delete-comment-btn').forEach(btn => {
                        btn.addEventListener('click', async function() {
                            if (confirm('Delete this comment?')) {
                                await deleteComment(this.dataset.commentId);
                            }
                        });
                    });
                }

                function setupSocialInteractions(activity) {
                    const isAuthenticated = FitPubAuth.isAuthenticated();

                    if (isAuthenticated) {
                        // Show comment form for authenticated users
                        document.getElementById('commentForm').style.display = 'block';

                        // Update like button based on activity data
                        if (activity.likedByCurrentUser) {
                            updateLikeButton(true);
                        }

                        // Setup like button click handler
                        document.getElementById('likeBtn').addEventListener('click', handleLikeClick);

                        // Show comment form for authenticated users
                        document.getElementById('commentForm').style.display = 'block';

                        // Setup comment form submit handler
                        document.getElementById('addCommentForm').addEventListener('submit', handleCommentSubmit);
                    } else {
                        // Show login prompt for non-authenticated users
                        document.getElementById('loginPrompt').style.display = 'block';
                        // Hide like button for non-authenticated users
                        document.getElementById('likeBtn').style.display = 'none';
                    }
                }

                async function handleLikeClick(event) {
                    event.preventDefault();
                    const btn = event.currentTarget;
                    const isLiked = btn.classList.contains('btn-danger');

                    try {
                        if (isLiked) {
                            // Unlike
                            const response = await FitPubAuth.authenticatedFetch(
                                `/api/activities/${activityId}/likes`,
                                { method: 'DELETE' }
                            );

                            if (response.ok) {
                                updateLikeButton(false);
                                loadLikes(); // Reload likes list
                            }
                        } else {
                            // Like
                            const response = await FitPubAuth.authenticatedFetch(
                                `/api/activities/${activityId}/likes`,
                                { method: 'POST' }
                            );

                            if (response.ok) {
                                updateLikeButton(true);
                                loadLikes(); // Reload likes list
                            }
                        }
                    } catch (error) {
                        console.error('Error toggling like:', error);
                        FitPub.showAlert('Failed to update like. Please try again.', 'danger');
                    }
                }

                function updateLikeButton(isLiked) {
                    const btn = document.getElementById('likeBtn');
                    const btnText = document.getElementById('likeBtnText');
                    const icon = btn.querySelector('i');

                    if (isLiked) {
                        btn.classList.remove('btn-outline-danger');
                        btn.classList.add('btn-danger');
                        icon.classList.remove('bi-heart');
                        icon.classList.add('bi-heart-fill');
                        btnText.textContent = 'Liked';
                    } else {
                        btn.classList.remove('btn-danger');
                        btn.classList.add('btn-outline-danger');
                        icon.classList.remove('bi-heart-fill');
                        icon.classList.add('bi-heart');
                        btnText.textContent = 'Like';
                    }
                }

                async function handleCommentSubmit(event) {
                    event.preventDefault();

                    const contentInput = document.getElementById('commentContent');
                    const content = contentInput.value.trim();

                    if (!content) return;

                    try {
                        const response = await FitPubAuth.authenticatedFetch(
                            `/api/activities/${activityId}/comments`,
                            {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ content })
                            }
                        );

                        if (response.ok) {
                            contentInput.value = '';
                            loadComments(); // Reload comments list
                            FitPub.showAlert('Comment posted successfully', 'success');
                        } else {
                            throw new Error('Failed to post comment');
                        }
                    } catch (error) {
                        console.error('Error posting comment:', error);
                        FitPub.showAlert('Failed to post comment. Please try again.', 'danger');
                    }
                }

                async function deleteComment(commentId) {
                    try {
                        const response = await FitPubAuth.authenticatedFetch(
                            `/api/activities/${activityId}/comments/${commentId}`,
                            { method: 'DELETE' }
                        );

                        if (response.ok) {
                            loadComments(); // Reload comments list
                            FitPub.showAlert('Comment deleted successfully', 'success');
                        } else {
                            throw new Error('Failed to delete comment');
                        }
                    } catch (error) {
                        console.error('Error deleting comment:', error);
                        FitPub.showAlert('Failed to delete comment. Please try again.', 'danger');
                    }
                }

                function escapeHtml(text) {
                    const div = document.createElement('div');
                    div.textContent = text;
                    return div.innerHTML;
                }

                // Delete functionality
                document.getElementById('deleteBtn').addEventListener('click', function() {
                    const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
                    modal.show();
                });

                document.getElementById('confirmDeleteBtn').addEventListener('click', async function() {
                    try {
                        const response = await FitPubAuth.authenticatedFetch(
                            `/api/activities/${activityId}`,
                            { method: 'DELETE' }
                        );

                        if (response.ok) {
                            // Close modal and redirect
                            const modal = bootstrap.Modal.getInstance(document.getElementById('deleteModal'));
                            modal.hide();

                            FitPub.showAlert('Activity deleted successfully', 'success');

                            setTimeout(() => {
                                window.location.href = '/activities';
                            }, 1000);
                        } else {
                            throw new Error('Failed to delete activity');
                        }
                    } catch (error) {
                        console.error('Delete error:', error);
                        FitPub.showAlert('Failed to delete activity. Please try again.', 'danger');
                    }
                });

                // Helper functions
                function formatDistance(meters) {
                    if (!meters) return 'N/A';
                    if (meters >= 1000) {
                        return (meters / 1000).toFixed(2) + ' km';
                    }
                    return Math.round(meters) + ' m';
                }

                function formatDuration(seconds) {
                    if (!seconds) return 'N/A';
                    const hours = Math.floor(seconds / 3600);
                    const minutes = Math.floor((seconds % 3600) / 60);
                    const secs = Math.floor(seconds % 60);

                    const parts = [];
                    if (hours > 0) parts.push(hours + 'h');
                    if (minutes > 0) parts.push(minutes + 'm');
                    if (secs > 0 || parts.length === 0) parts.push(secs + 's');

                    return parts.join(' ');
                }

                function formatPace(secondsPerKm) {
                    if (!secondsPerKm) return 'N/A';
                    const minutes = Math.floor(secondsPerKm / 60);
                    const seconds = Math.floor(secondsPerKm % 60);
                    return `${minutes}:${seconds.toString().padStart(2, '0')}/km`;
                }

                function getVisibilityIcon(visibility) {
                    switch (visibility) {
                        case 'PUBLIC': return 'globe';
                        case 'FOLLOWERS': return 'people';
                        case 'PRIVATE': return 'lock';
                        default: return 'question-circle';
                    }
                }
            });
        </script>
    </th:block>
</body>
</html>
