/**
 * @file teamsButton.js
 * @description Hantering av "Anslut Teams"-knappen för StatusNotifier Extension
 * 
 * Author: Linus Olofsson - Iver 
 * Date: 2025-07-03 
 * Last modified: Linus Olofsson (2026-02-24) - SSO-inloggning via Microsoft Entra ID
 * 
 * @purpose Hantera "Anslut Teams"-knappen med SSO-inloggning
 * @invoked_by popup.js
 * @invokes api/ssoAuth.js
 */

import { loginWithSSO, logout, isAuthenticated, getCurrentUser, fetchTeamsPresence, getValidAccessToken } from '../api/ssoAuth.js';

// Initiera teamsButton-hanterare
const initTeamsButton = async () => {
    try {
        console.log('Initializing teams button handler...');
        
        // Hitta teams-knappen
        const teamsButton = document.getElementById('teamsBtn');
        if (!teamsButton) {
            console.error('Teams button not found in DOM');
            return;
        }
        
        // Lägg till klick-event
        teamsButton.addEventListener('click', handleTeamsButtonClick);
        
        // Kontrollera om användaren redan är inloggad
        await updateButtonState();
        
        console.log('Teams button handler initialized');
    } catch (error) {
        console.error('Error initializing teams button handler:', error);
    }
};

// Uppdatera knappens utseende baserat på inloggningsstatus
const updateButtonState = async () => {
    const teamsButton = document.getElementById('teamsBtn');
    if (!teamsButton) return;
    
    const authenticated = await isAuthenticated();
    
    if (authenticated) {
        const user = await getCurrentUser();
        const firstName = user?.givenName || user?.displayName?.split(' ')[0] || 'User';
        teamsButton.textContent = `✓ ${firstName}`;
        teamsButton.title = `Inloggad som ${user?.displayName || 'okänd'}\n${user?.mail || ''}\nKlicka för att logga ut`;
        teamsButton.classList.add('sso-logged-in');
    } else {
        teamsButton.textContent = 'Anslut Teams';
        teamsButton.title = 'Logga in med Microsoft SSO';
        teamsButton.classList.remove('sso-logged-in');
    }
};

// Hantera klick på teams-knappen
const handleTeamsButtonClick = async () => {
    try {
        console.log('Teams button clicked');
        
        const teamsButton = document.getElementById('teamsBtn');
        if (!teamsButton) return;
        
        const authenticated = await isAuthenticated();
        
        if (authenticated) {
            // Redan inloggad - visa alternativ att logga ut
            await handleLogout(teamsButton);
        } else {
            // Inte inloggad - starta SSO-inloggning
            await handleLogin(teamsButton);
        }
    } catch (error) {
        console.error('Error handling teams button click:', error);
        
        const teamsButton = document.getElementById('teamsBtn');
        if (teamsButton) {
            teamsButton.textContent = 'Anslut Teams';
            teamsButton.disabled = false;
        }
    }
};

// Hantera inloggning
const handleLogin = async (teamsButton) => {
    const originalText = teamsButton.textContent;
    teamsButton.textContent = 'Loggar in...';
    teamsButton.disabled = true;
    
    try {
        // Starta SSO-inloggning med Teams-scopes
        const authData = await loginWithSSO('teams');
        
        console.log('SSO login successful:', authData.userProfile?.displayName);
        
        // Spara användarens Spark-ID för assignedTo-filter
        if (authData.userProfile) {
            await chrome.storage.local.set({
                ssoUserProfile: authData.userProfile,
                ssoUserDisplayName: authData.userProfile.displayName,
                ssoUserEmail: authData.userProfile.mail,
                ssoUserId: authData.userProfile.id
            });
        }
        
        // Försök hämta Teams-presence
        try {
            const presence = await fetchTeamsPresence(authData.accessToken);
            if (presence) {
                await chrome.storage.local.set({ teamsPresence: presence });
                console.log('Teams presence:', presence.availability);
            }
        } catch (presenceError) {
            console.warn('Could not fetch Teams presence:', presenceError);
        }
        
        // Uppdatera knappens utseende
        await updateButtonState();
        teamsButton.disabled = false;
        
    } catch (error) {
        console.error('SSO login failed:', error);
        
        // Visa felmeddelande kort
        teamsButton.textContent = error.message?.includes('avbröts') ? 'Avbruten' : 'Fel vid inloggning';
        teamsButton.disabled = false;
        
        setTimeout(() => {
            teamsButton.textContent = originalText;
        }, 3000);
    }
};

// Hantera utloggning
const handleLogout = async (teamsButton) => {
    const user = await getCurrentUser();
    const userName = user?.displayName || 'okänd';
    
    // Enkel bekräftelse via knappen
    teamsButton.textContent = 'Loggar ut...';
    teamsButton.disabled = true;
    
    try {
        await logout();
        
        // Rensa sparad användardata
        await chrome.storage.local.remove([
            'ssoUserProfile', 
            'ssoUserDisplayName', 
            'ssoUserEmail', 
            'ssoUserId',
            'teamsPresence'
        ]);
        
        console.log(`User ${userName} logged out`);
        
        // Uppdatera knappens utseende
        await updateButtonState();
        teamsButton.disabled = false;
        
    } catch (error) {
        console.error('Logout failed:', error);
        teamsButton.textContent = 'Fel vid utloggning';
        teamsButton.disabled = false;
        
        setTimeout(async () => {
            await updateButtonState();
        }, 2000);
    }
};

// Exportera funktioner
export {
    initTeamsButton,
    updateButtonState
};
