// Pašreiz rediģējamā kalendāra ID
let currentCalendarId = null;

// Skaits katrai cilnei (kopīgotie, draugi, komandas)
let currentTabCounts = { shared: 0, friends: 0, teams: 0 };

// Atver kalendāra rediģēšanas modālo logu
function openEditModal(calendarId) {
    if (!calendarId) {
        console.error('No calendar ID provided');
        return;
    }

    currentCalendarId = calendarId;
    document.getElementById('editModal').style.display = 'block';
    loadCalendarData(calendarId);
}

// Aizver modālo logu un notīra laukus
function closeEditModal() {
    document.getElementById('editModal').style.display = 'none';
    document.getElementById('calendar_id').value = '';
    document.getElementById('calendar_name').value = '';
    hideMessage();
}

// Pārslēdz cilnes (Shared / Friends / Teams)
function switchTab(tabName) {
    // Noņem "active" klasi visām cilnēm
    document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
    event.target.classList.add('active');
    
    // Paslēpj visu cilņu saturu
    document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
    document.getElementById('tab-' + tabName).classList.add('active');
}

// Ielādē kalendāra datus (kopīgošanas informāciju)
function loadCalendarData(calendarId) {
    if (!calendarId) return;

    // Iegūst kalendāra pamatdatus un jau pievienotos draugus
    fetch(`ajax/get_calendar.php?id=${calendarId}`)
        .then(response => response.json())
        .then(data => {
            if (!data.calendar) {
                showMessage('Calendar not found', 'error');
                return;
            }

            document.getElementById('calendar_id').value = data.calendar.id;
            document.getElementById('calendar_name').value = data.calendar.name;

            // Attēlo kopīgoto personu sarakstu
            renderSharedList(data.friends);

            // Atjaunina cilnes skaitu
            currentTabCounts.shared = data.friends.length;
            updateTabLabels();
        })
        .catch(error => {
            console.error(error);
            showMessage('Error loading calendar data', 'error');
        });

    // Iegūst pieejamos draugus un komandas
    fetch(`ajax/get_teams.php?calendar_id=${calendarId}`)
        .then(response => response.json())
        .then(data => {
            renderAvailableFriends(data.friends);
            renderAvailableTeams(data.teams);

            // Atjaunina cilņu skaitītājus
            currentTabCounts.friends = data.friends.length;
            currentTabCounts.teams = data.teams.length;
            updateTabLabels();
        })
        .catch(error => {
            console.error(error);
            showMessage('Error loading friends and teams', 'error');
        });
}

// Atjaunina cilņu nosaukumus ar skaitu
function updateTabLabels() {
    const tabs = document.querySelectorAll('.tab');
    tabs[0].textContent = `Currently Shared (${currentTabCounts.shared})`;
    tabs[1].textContent = `Add Friends (${currentTabCounts.friends})`;
    tabs[2].textContent = `Add Teams (${currentTabCounts.teams})`;
}

// Attēlo personas, kurām jau ir piekļuve kalendāram
function renderSharedList(friends) {
    const sharedList = document.getElementById('sharedList');
    
    if (friends.length === 0) {
        sharedList.innerHTML = '<div class="no-items">No one has access yet. Add friends or teams!</div>';
        return;
    }
    
    sharedList.innerHTML = friends.map(friend => `
        <div class="friend-item" id="shared-${friend.id}">
            <div class="friend-info">
                <span class="friend-name">${friend.name}</span>
            </div>
            <div class="friend-actions">
                <span class="access-badge ${friend.can_edit ? 'editor' : 'viewer'}">
                    ${friend.can_edit ? 'Editor' : 'Viewer'}
                </span>
                <!-- Maina piekļuves līmeni -->
                <button type="button" class="btn-toggle" onclick="toggleFriendAccess(${friend.id})">
                    Switch
                </button>
                <!-- Noņem personu no kalendāra -->
                <button type="button" class="btn-remove" onclick="removeFriend(${friend.id})">
                    Remove
                </button>
            </div>
        </div>
    `).join('');
}

// Attēlo pieejamos draugus pievienošanai
function renderAvailableFriends(friends) {
    const friendsList = document.getElementById('availableFriendsList');
    
    if (friends.length === 0) {
        friendsList.innerHTML = '<div class="no-items">All your friends are already added to this calendar!</div>';
        return;
    }
    
    friendsList.innerHTML = friends.map(friend => `
        <div class="friend-item" id="available-friend-${friend.id}">
            <div class="friend-info">
                <span class="friend-name">${friend.name}</span>
                <span class="friend-email">${friend.email}</span>
            </div>
            <div class="friend-actions">
                <!-- Pievieno draugu kalendāram -->
                <button type="button" class="btn-add" onclick="addFriendToCalendar(${friend.id})">
                    + Add to Calendar
                </button>
            </div>
        </div>
    `).join('');
}

// Attēlo pieejamās komandas
function renderAvailableTeams(teams) {
    const teamsList = document.getElementById('availableTeamsList');
    
    if (teams.length === 0) {
        teamsList.innerHTML = '<div class="no-items">No teams created yet. Create teams in the Teams section!</div>';
        return;
    }
    
    teamsList.innerHTML = teams.map(team => `
        <div class="team-item" id="available-team-${team.id}">
            <div class="team-info">
                <span class="team-name">${team.name}</span>
                <span class="team-members">${team.member_count} member(s)</span>
            </div>
            <div class="friend-actions">
                <!-- Pievieno visu komandu kalendāram -->
                <button type="button" class="btn-add" onclick="addTeamToCalendar(${team.id})">
                    + Add Team to Calendar
                </button>
            </div>
        </div>
    `).join('');
}

// Pievieno draugu kalendāram
function addFriendToCalendar(friendId) {
    const formData = new FormData();
    formData.append('friend_id', friendId);
    formData.append('calendar_id', currentCalendarId);
    
    fetch('ajax/add_friend.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(result => {
        if (result === 'OK') {
            showMessage('Friend added successfully!', 'success');
            loadCalendarData(currentCalendarId);
        } else {
            showMessage(result, 'error');
        }
    })
    .catch(error => {
        showMessage('Error adding friend', 'error');
    });
}

// Pievieno komandu kalendāram
function addTeamToCalendar(teamId) {
    const formData = new FormData();
    formData.append('team_id', teamId);
    formData.append('calendar_id', currentCalendarId);
    
    fetch('ajax/add_team.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(result => {
        if (result.startsWith('OK:')) {
            const count = result.split(':')[1];
            showMessage(`Team added! ${count} member(s) added to calendar.`, 'success');
            loadCalendarData(currentCalendarId);
        } else {
            showMessage(result, 'error');
        }
    })
    .catch(error => {
        showMessage('Error adding team', 'error');
    });
}

// Maina drauga piekļuves līmeni (skatītājs / redaktors)
function toggleFriendAccess(friendId) {
    fetch(`ajax/toggle_friend.php?id=${friendId}`)
        .then(response => response.text())
        .then(result => {
            if (result === 'OK') {
                showMessage('Access level updated!', 'success');
                loadCalendarData(currentCalendarId);
            }
        })
        .catch(error => {
            showMessage('Error updating access', 'error');
        });
}

// Noņem personu no kalendāra
function removeFriend(friendId) {
    if (!confirm('Remove this person from calendar?')) return;
    
    fetch(`ajax/remove_friend.php?id=${friendId}`)
        .then(response => response.text())
        .then(result => {
            if (result === 'OK') {
                showMessage('Person removed', 'success');
                loadCalendarData(currentCalendarId);
            }
        })
        .catch(error => {
            showMessage('Error removing person', 'error');
        });
}

// Saglabā kalendāra izmaiņas
document.getElementById('editCalendarForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    fetch('ajax/save_calendar.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(result => {
        if (result === 'OK') {
            showMessage('Calendar saved successfully!', 'success');
            setTimeout(() => {
                location.reload();
            }, 1000);
        } else {
            showMessage('Error saving calendar', 'error');
        }
    })
    .catch(error => {
        showMessage('Error saving calendar', 'error');
    });
});

// Parāda paziņojumu modālajā logā
function showMessage(text, type) {
    const messageDiv = document.getElementById('modalMessage');
    messageDiv.textContent = text;
    messageDiv.className = `message ${type}`;
    messageDiv.style.display = 'block';
    
    setTimeout(() => {
        hideMessage();
    }, 3000);
}

// Paslēpj paziņojumu
function hideMessage() {
    const messageDiv = document.getElementById('modalMessage');
    messageDiv.style.display = 'none';
}

// Aizver modālo logu, ja klikšķis ārpus tā
window.onclick = function(event) {
    const modal = document.getElementById('editModal');
    if (event.target === modal) {
        closeEditModal();
    }
}