<script lang="ts">
    import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore, discordDataStore, client, TAServerAPIPort } from "$lib/stores";
    import { onMount, onDestroy } from "svelte";
    import { bkAPIUrl } from '$lib/config.json';
    import AddNewAuthorisedUser from "$lib/components/popups/AddNewAuthorisedUser.svelte";
    //@ts-ignore
    import { Match, Tournament, TAClient, Response_ResponseType } from 'moons-ta-client';
    import { writable } from "svelte/store";
    import SideMenu from "$lib/components/menus/SideMenuTournaments.svelte";
    import InfoPopup from "$lib/components/notifications/InfoPopup.svelte";
    import { bufferToImageUrl, convertImageToUint8Array, linkToUint8Array } from "$lib/services/taImages.js";
    import Popup from "$lib/components/notifications/Popup.svelte";
    import { goto } from "$app/navigation";

    export let data;

    const tournamentGuid: string = data.tournamentGuid;
    let tournament: Tournament | undefined;
    let isLoading = false;
    let error: string | null = null;
    
    // Tournament settings
    let tournamentName: string = "";
    let tournamentImage: string = "https://api.dicebear.com/7.x/identicon/svg?seed=tournament";
    let enableMapPools: boolean = false;
    let enableTeams: boolean = false;
    let showTournamentButton: boolean = true;
    let showQualifierButton: boolean = true;
    let hideTournament: boolean = false;
    let scoreUpdateFrequency: number = 1;
    let bannedMods: string[] = [];
    let newBannedMod: string = "";
    let authorizedUsers: any[] = [];
    
    // Popup state
    let showPopup: boolean = false;
    let popupContent: string = "";
    let showAddUserPopup = false;
    let showSuccessfullySaved = false;
    
    // File upload
    let fileInput: HTMLInputElement;
    let imagePreview: string | null = null;

    // Create the original state for the object which keeps trach of what parts of the tournament have been edited
    let modifiedObject = {
        name: false,
        image: false,
        enableMapPools: false,
        enableTeams: false,
        showTournamentButton: false,
        showQualifierButton: false,
        hideTournament: false,
        scoreUpdateFrequency: false,
        bannedMods: false
    }

    enum Permissions {
        "None" = 0,
        "View Only" = 1,
        "Administrator" = 2,
        "View and Administrator" = 3
    }
    
    // Remove 'Bearer ' from the token
    if($authTokenStore) {
        const cleanToken = $authTokenStore.replace('Bearer ', '');
        client.setAuthToken(cleanToken);
    }
    
    function openInfoPopup(content: string) {
        popupContent = content;
        showPopup = true;
    }
    
    function closePopup() {
        showPopup = false;
    }
    
    function handleImageUpload() {
        modifiedObject.image = true;
        fileInput.click();
    }
    
    function onFileSelected(event: Event) {
        const target = event.target as HTMLInputElement;
        const files = target.files;
        
        if (files && files.length > 0) {
            const file = files[0];
            const reader = new FileReader();
            
            reader.onload = (e) => {
                const result = e.target?.result as string;
                imagePreview = result;
                tournamentImage = result;
            };
            
            reader.readAsDataURL(file);
        }
    }
    
    function addBannedMod(event: KeyboardEvent) {
        modifiedObject.bannedMods = true;
        if (event.key === 'Enter' && newBannedMod.trim() !== '') {
            if (!bannedMods.includes(newBannedMod.trim())) {
                bannedMods = [...bannedMods, newBannedMod.trim()];
            }
            newBannedMod = '';
        }
    }
    
    function removeBannedMod(mod: string) {
        modifiedObject.bannedMods = true;
        bannedMods = bannedMods.filter(m => m !== mod);
    }
    
    async function removeAuthorisedUser(discordId: string) {
        let removeAuthuserResponse = await client.removeAuthorizedUser(tournamentGuid, discordId)
        authorizedUsers = authorizedUsers.filter(user => user.discordId !== discordId);
    }

    async function handleAddUser(event: CustomEvent) {
        const userData = event.detail;
        console.log('Adding user:', userData);
        
        try {
            let addAuthorizedUserResult = await client.addAuthorizedUser(tournamentGuid, userData.discordId, userData.permission);
            
            // If successful, add to the authorizedUsers array
            if (addAuthorizedUserResult.type === Response_ResponseType.Success) {
                authorizedUsers = [...authorizedUsers, userData];
            }
        } catch (err) {
            console.error('Error adding user:', err);
            error = "Failed to add user, please view console, screenshot it and send it to serverbp or matrikmoon on Discord.";
        }
    }

    function removeImage() {
        imagePreview = "/talogo.png";
        tournamentImage = "/talogo.png";
        modifiedObject.image = true;
    }

    function openAddUserPopup() {
        showAddUserPopup = true;
    }
    
    function closeAddUserPopup() {
        showAddUserPopup = false;
    }

    function closeNotification() {
        showSuccessfullySaved = false;
    }
    
    async function saveSettings() {
        if(!tournament) return;

        if(modifiedObject.name) {
            const setTournamentName = await client.setTournamentName(tournamentGuid, tournamentName);
            console.log(setTournamentName)
        }

        if(modifiedObject.image) {
            const setTournamentImage = await client.setTournamentImage(tournamentGuid, await linkToUint8Array(tournamentImage));
            console.log(setTournamentImage);
        }

        if(modifiedObject.bannedMods) {
            const setTournamentBannedMods = await client.setTournamentBannedMods(tournamentGuid, bannedMods);
            console.log(setTournamentBannedMods);
        }

        // There is some wanky logic here. When they are equal, it means one has changed.
        if(tournament.settings?.allowUnauthorizedView == hideTournament) {
            const setTournamentAllowUnauthorizedView = await client.setTournamentAllowUnauthorizedView(tournamentGuid, !hideTournament);
            console.log(setTournamentAllowUnauthorizedView);
        }

        if(tournament.settings?.enablePools !== enableMapPools) {
            const setTournamentEnablePools = await client.setTournamentEnablePools(tournamentGuid, enableMapPools);
            console.log(setTournamentEnablePools);
        }

        if(tournament.settings?.enableTeams !== enableTeams) {
            const setTournamentEnableTeams = await client.setTournamentEnableTeams(tournamentGuid, enableTeams);
            console.log(setTournamentEnableTeams);
        }

        if(tournament.settings?.showTournamentButton !== showTournamentButton) {
            const setTournamentShowTournamentButton = await client.setTournamentShowTournamentButton(tournamentGuid, showTournamentButton);
            console.log(setTournamentShowTournamentButton);
        }

        if(tournament.settings?.showQualifierButton !== showQualifierButton) {
            const setTournamentShowQualifierButton = await client.setTournamentShowQualifierButton(tournamentGuid, showQualifierButton);
            console.log(setTournamentShowQualifierButton);
        }

        if(tournament.settings?.scoreUpdateFrequency !== scoreUpdateFrequency) {
            const setTournamentScoreUpdateFrequency = await client.setTournamentScoreUpdateFrequency(tournamentGuid, scoreUpdateFrequency);
            console.log(setTournamentScoreUpdateFrequency);
        }

        showSuccessfullySaved = true;
    }

    async function deleteTournament() {
        await client.deleteTournament(tournamentGuid);

        goto('/tournaments');
    }

    async function fetchTournamentData() {
        if (!$authTokenStore) {
            window.location.href = '/discordAuth';
            return;
        }
        
        isLoading = true;
        error = null;
        
        try {
            if(!client.isConnected) {
                const connectResult = await client.connect($TAServerUrl, $TAServerPort);

                if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) {
                    throw new Error(connectResult.details.connect.message);
                }
            }
            
            if(!client.stateManager.getTournament(tournamentGuid)!.users.some(user => user.guid == client.stateManager.getSelfGuid())) {
                const joinResult = await client.joinTournament(tournamentGuid);
                if (joinResult.details.oneofKind !== 'join' || joinResult.type === Response_ResponseType.Fail) {
                    throw new Error('Could not join tournament');
                }
            }            

            tournament = client.stateManager.getTournament(tournamentGuid)!;
            
            // Set initial values from tournament data
            if (tournament) {
                tournamentName = tournament.settings?.tournamentName || "";
                tournamentImage = tournament.settings!.tournamentImage && tournament.settings!.tournamentImage.length > 2 ? `https://${$TAServerUrl}:${$TAServerAPIPort}/api/file/${tournament.settings!.tournamentImage}` : '/talogo.png';
                enableMapPools = tournament.settings?.enablePools || false;
                enableTeams = tournament.settings?.enableTeams || false;
                showTournamentButton = tournament.settings?.showTournamentButton !== false;
                showQualifierButton = tournament.settings?.showQualifierButton !== false;
                hideTournament = !tournament.settings?.allowUnauthorizedView || false;
                scoreUpdateFrequency = tournament.settings?.scoreUpdateFrequency || 1;
                bannedMods = tournament.settings?.bannedMods || [];
                
                // For demo purposes, populate authorised users
                // This would typically come from the tournament object
                let authorisedUserRes = await client.getAuthorizedUsers(tournamentGuid);
                console.log(authorisedUserRes)
                authorizedUsers = (authorisedUserRes as any).details.getAuthorizedUsers.authorizedUsers.filter((user: any) => user.discordId !== $discordDataStore.id) || [
                    {
                        guid: "user1",
                        name: "Failed Data",
                        discordInfo: {
                            username: "TourneyAdmin",
                            avatarUrl: "https://api.dicebear.com/7.x/avataaars/svg?seed=admin"
                        },
                        permissions: "admin"
                    },
                    {
                        guid: "user2",
                        name: "Failed Data",
                        discordInfo: {
                            username: "TourneyViewer",
                            avatarUrl: "https://api.dicebear.com/7.x/avataaars/svg?seed=viewer"
                        },
                        permissions: "view only"
                    }
                ];
            }
            
        } catch (err) {
            console.error('Error fetching tournament data:', err);
            error = err instanceof Error ? err.message : 'An unknown error occurred';
        } finally {
            isLoading = false;
        }
    }

    onMount(async() => {
        if ($authTokenStore) {
            await fetchTournamentData();
        } else {
            window.location.href = "/discordAuth"
        }
    });
</script>

<div class="layout">
    <main class="dashboard">
        <SideMenu currentPage="settings" tournamentName={tournament?.settings?.tournamentName} tournamnentGuid={tournamentGuid} />
        
        <div class="content-area">
            <div class="content-header">
                <h2>Tournament Settings</h2>
                <div class="actions">
                    <button class="action-button save" on:click={saveSettings}>
                        <span class="material-icons">save</span>
                        Save Changes
                    </button>
                    <button class="action-button refresh" on:click={fetchTournamentData}>
                        <span class="material-icons">refresh</span>
                        Refresh
                    </button>
                    <button class="action-button remove" on:click={deleteTournament}>
                        <span class="material-icons">delete</span>
                        Delete Tournament
                    </button>
                </div>
            </div>
            
            {#if isLoading}
                <div class="loading">
                    <div class="spinner"></div>
                    <p>Loading tournament data...</p>
                </div>
            {:else if error}
                <div class="error-container">
                    <span class="material-icons">error_outline</span>
                    <p>{error}</p>
                    <button class="retry-button" on:click={fetchTournamentData}>Retry</button>
                </div>
            {:else}
                <div class="settings-grid">
                    <!-- Basic Settings Section -->
                    <div class="settings-section">
                        <h3>Basic Settings</h3>
                        
                        <div class="settings-group">
                            <div class="setting-row">
                                <div class="setting-label">
                                    <label for="tournament-name">Tournament Name</label>
                                    <button class="info-button" on:click={() => openInfoPopup("The name of your tournament that will be displayed to participants and viewers.")}>
                                        <span class="material-icons">info</span>
                                    </button>
                                </div>
                                <input 
                                    type="text" 
                                    id="tournament-name" 
                                    class="setting-input" 
                                    bind:value={tournamentName} 
                                    placeholder="Enter tournament name"
                                />
                            </div>
                            
                            <div class="setting-row">
                                <div class="setting-label">
                                    <!-- svelte-ignore a11y-label-has-associated-control -->
                                    <label>Tournament Image</label>
                                    <button class="info-button" on:click={() => openInfoPopup("The logo or image that represents your tournament. Recommended size: 512x512px.")}>
                                        <span class="material-icons">info</span>
                                    </button>
                                </div>
                                <div class="image-upload-container">
                                    <div class="image-preview-wrapper">
                                        <div class="image-preview">
                                            <img src={imagePreview || tournamentImage} alt="Tournament logo" />
                                        </div>
                                        <div class="image-upload-actions">
                                            <button class="action-button upload" on:click={handleImageUpload}>
                                                <span class="material-icons">upload</span>
                                                Upload Image
                                            </button>
                                            {#if imagePreview || tournamentImage}
                                                <button class="action-button remove" on:click={removeImage}>
                                                    <span class="material-icons">delete</span>
                                                    Remove
                                                </button>
                                            {/if}
                                        </div>
                                    </div>
                                    <p class="image-upload-help">Recommended size: 512x512px</p>
                                    <input 
                                        type="file" 
                                        accept="image/*" 
                                        style="display: none" 
                                        bind:this={fileInput} 
                                        on:change={onFileSelected}
                                    />
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Feature Toggles Section -->
                    <div class="settings-section">
                        <h3>Features</h3>
                        
                        <div class="settings-group">
                            <div class="setting-row toggle-row">
                                <div class="setting-label">
                                    <label for="map-pools">Enable Map Pools</label>
                                    <button class="info-button" on:click={() => openInfoPopup("When enabled, tournament organizers can create map pools for matches.")}>
                                        <span class="material-icons">info</span>
                                    </button>
                                </div>
                                <label class="toggle">
                                    <input type="checkbox" id="map-pools" bind:checked={enableMapPools}>
                                    <span class="slider"></span>
                                </label>
                            </div>
                            
                            <div class="setting-row toggle-row">
                                <div class="setting-label">
                                    <label for="teams">Enable Teams</label>
                                    <button class="info-button" on:click={() => openInfoPopup("When enabled, players can be select which team they are on in the match lobby.")}>
                                        <span class="material-icons">info</span>
                                    </button>
                                </div>
                                <label class="toggle">
                                    <input type="checkbox" id="teams" bind:checked={enableTeams}>
                                    <span class="slider"></span>
                                </label>
                            </div>
                            
                            <div class="setting-row toggle-row">
                                <div class="setting-label">
                                    <label for="tournament-button">Show Tournament Button</label>
                                    <button class="info-button" on:click={() => openInfoPopup("When enabled, the tournament button will be visible in game after connecting to the server.")}>
                                        <span class="material-icons">info</span>
                                    </button>
                                </div>
                                <label class="toggle">
                                    <input type="checkbox" id="tournament-button" bind:checked={showTournamentButton}>
                                    <span class="slider"></span>
                                </label>
                            </div>
                            
                            <div class="setting-row toggle-row">
                                <div class="setting-label">
                                    <label for="qualifier-button">Show Qualifier Button</label>
                                    <button class="info-button" on:click={() => openInfoPopup("When enabled, the qualifier button will be visible in game after connecting to the server.")}>
                                        <span class="material-icons">info</span>
                                    </button>
                                </div>
                                <label class="toggle">
                                    <input type="checkbox" id="qualifier-button" bind:checked={showQualifierButton}>
                                    <span class="slider"></span>
                                </label>
                            </div>
                            
                            <div class="setting-row toggle-row">
                                <div class="setting-label">
                                    <label for="hide-tournament">Hide Tournament</label>
                                    <button class="info-button" on:click={() => openInfoPopup("When enabled, the tournament will be hidden from public listings and the in game list.")}>
                                        <span class="material-icons">info</span>
                                    </button>
                                </div>
                                <label class="toggle">
                                    <input type="checkbox" id="hide-tournament" bind:checked={hideTournament}>
                                    <span class="slider"></span>
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Advanced Settings Section -->
                    <div class="settings-section">
                        <h3>Advanced Settings</h3>
                        
                        <div class="settings-group">
                            <div class="setting-row">
                                <div class="setting-label">
                                    <label for="score-update">Score Update Frequency (frames)</label>
                                    <button class="info-button" on:click={() => openInfoPopup("How frequently the score should update during gameplay, measured in frames. Lower values mean more frequent updates but potentially higher server load.")}>
                                        <span class="material-icons">info</span>
                                    </button>
                                </div>
                                <input 
                                    type="number" 
                                    id="score-update" 
                                    class="setting-input" 
                                    bind:value={scoreUpdateFrequency} 
                                    min="1"
                                    step="1"
                                />
                            </div>
                            
                            <div class="setting-row">
                                <div class="setting-label">
                                    <label for="banned-mods">Banned Mods</label>
                                    <button class="info-button" on:click={() => openInfoPopup("List of mods that are not allowed in this tournament. Enter mod names and press Enter to add them.")}>
                                        <span class="material-icons">info</span>
                                    </button>
                                </div>
                                <div class="banned-mods-container">
                                    <input 
                                        type="text" 
                                        id="banned-mods" 
                                        class="setting-input" 
                                        bind:value={newBannedMod} 
                                        placeholder="Type a mod name and press Enter"
                                        on:keydown={addBannedMod}
                                    />
                                    <div class="banned-mods-list">
                                        {#if bannedMods.length === 0}
                                            <p class="no-mods">No banned mods added yet</p>
                                        {:else}
                                            {#each bannedMods as mod}
                                                <div class="mod-tag">
                                                    <span>{mod}</span>
                                                    <button class="remove-mod" on:click={() => removeBannedMod(mod)}>
                                                        <span class="material-icons">close</span>
                                                    </button>
                                                </div>
                                            {/each}
                                        {/if}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="settings-section full-width">
                    <h3>Authorised Users</h3>
                    
                    <div class="settings-group">
                        <div class="authorized-users-container">
                            <button class="action-button add-user" on:click={openAddUserPopup}>
                                <span class="material-icons">person_add</span>
                                Add User
                            </button>
                            {#if authorizedUsers.length === 0}
                                <p class="no-users">No authorized users added yet</p>
                            {:else}
                                <div class="user-cards-grid">
                                    {#each authorizedUsers as user}
                                        <div class="user-card">
                                            <img 
                                                class="user-avatar" 
                                                src={user.discordAvatarUrl || "https://api.dicebear.com/7.x/avataaars/svg?seed=default"} 
                                                alt={user.discordUsername || "User avatar"}
                                            />
                                            <div class="user-info">
                                                <h4>{user.name || user.discordUsername || "Unknown User"}</h4>
                                                <p class="user-permission">{Permissions[user.permission]}</p>
                                            </div>
                                            <button class="remove-user" on:click={() => removeAuthorisedUser(user.discordId)}>
                                                <span class="material-icons">delete</span>
                                            </button>
                                        </div>
                                    {/each}
                                </div>
                            {/if}
                        </div>
                    </div>
                </div>
            {/if}
        </div>

        <AddNewAuthorisedUser 
            isOpen={showAddUserPopup}
            tournamentGuid={tournamentGuid}
            taClient={client}
            on:close={closeAddUserPopup}
            on:addUser={handleAddUser}
        />

        <Popup
            bind:open={showSuccessfullySaved}
            message="Successfully saved the tournament information!"
            icon="check"
            iconColor="success"
            buttons={[]}
            on:close={closeNotification}
        />
    </main>
</div>

{#if showPopup}
    <InfoPopup content={popupContent} onClose={closePopup} />
{/if}

<style>
    /* Settings grid */
    .settings-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 1.5rem;
        margin-bottom: 1.5rem;
    }
    
    /* Settings sections */
    .settings-section {
        background-color: var(--bg-secondary);
        border-radius: 0.75rem;
        padding: 1.5rem;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    .settings-section h3 {
        font-size: 1.25rem;
        font-weight: 500;
        margin-bottom: 1.25rem;
        color: var(--text-primary);
    }

    .settings-section.full-width {
        grid-column: 1 / -1;
        margin-top: 1.5rem;
    }
    
    .settings-group {
        display: flex;
        flex-direction: column;
        gap: 1.25rem;
    }
    
    /* Setting rows */
    .setting-row {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }
    
    .setting-label {
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    
    .setting-label label {
        font-weight: 500;
        font-size: 0.9375rem;
    }
    
    .setting-input {
        background-color: var(--bg-tertiary);
        border: none;
        border-radius: 0.375rem;
        padding: 0.625rem 0.75rem;
        color: var(--text-primary);
        font-size: 0.9375rem;
        width: 100%;
    }
    
    .setting-input:focus {
        outline: 2px solid var(--accent-color);
    }
    
    /* Toggle rows */
    .toggle-row {
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
    }
    
    /* Toggle switch */
    .toggle {
        position: relative;
        display: inline-block;
        width: 3rem;
        height: 1.5rem;
    }
    
    .toggle input {
        opacity: 0;
        width: 0;
        height: 0;
    }
    
    .slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: var(--bg-tertiary);
        transition: .4s;
        border-radius: 1.5rem;
    }
    
    .slider:before {
        position: absolute;
        content: "";
        height: 1.125rem;
        width: 1.125rem;
        left: 0.1875rem;
        bottom: 0.1875rem;
        background-color: var(--text-secondary);
        transition: .4s;
        border-radius: 50%;
    }
    
    input:checked + .slider {
        background-color: var(--accent-color);
    }
    
    input:checked + .slider:before {
        transform: translateX(1.5rem);
        background-color: white;
    }
    
    /* Info button */
    .info-button {
        background: none;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--accent-color);
        padding: 0;
        font-size: 0.875rem;
    }
    
    .info-button .material-icons {
        font-size: 1.125rem;
    }
    
    .info-button:hover {
        color: var(--accent-hover);
    }
    
    /* Image upload */
    .image-upload-container {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
    }
    
    .image-preview-wrapper {
        display: flex;
        gap: 1.5rem;
        align-items: center;
    }

    .image-preview {
        width: 8rem;
        height: 8rem;
        border-radius: 0.75rem;
        overflow: hidden;
        background-color: var(--bg-tertiary);
        border: 2px dashed var(--accent-color);
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .image-preview img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    .image-upload-actions {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }

    .image-upload-help {
        color: var(--text-secondary);
        font-size: 0.8125rem;
        margin: 0;
    }

    .action-button.upload {
        background-color: var(--accent-color);
    }

    .action-button.remove {
        background-color: var(--bg-tertiary);
        color: #ff5555;
    }

    .action-button.remove:hover {
        background-color: rgba(255, 85, 85, 0.1);
    }
    
    /* Banned mods styling */
    .banned-mods-container {
        display: flex;
        flex-direction: column;
        gap: 1rem;
        width: 100%;
    }
    
    .banned-mods-list {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
    }
    
    .mod-tag {
        display: flex;
        align-items: center;
        gap: 0.25rem;
        background-color: var(--bg-tertiary);
        border-radius: 1rem;
        padding: 0.375rem 0.75rem;
        font-size: 0.875rem;
    }
    
    .mod-tag .remove-mod {
        background: none;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--text-secondary);
        padding: 0;
    }
    
    .mod-tag .remove-mod:hover {
        color: var(--text-primary);
    }
    
    .mod-tag .remove-mod .material-icons {
        font-size: 1rem;
    }
    
    .no-mods {
        color: var(--text-secondary);
        font-style: italic;
        font-size: 0.875rem;
    }
    
    /* Authorized users styling */
    .authorized-users-container {
        display: flex;
        flex-direction: column;
        gap: 1rem;
    }
    
    .user-card {
        display: flex;
        align-items: center;
        gap: 1rem;
        background-color: var(--bg-tertiary);
        border-radius: 0.5rem;
        padding: 0.75rem 1rem;
    }
    
    .user-avatar {
        width: 2.5rem;
        height: 2.5rem;
        border-radius: 50%;
        object-fit: cover;
    }
    
    .user-info {
        flex: 1;
    }
    
    .user-info h4 {
        margin: 0;
        font-size: 0.9375rem;
        font-weight: 500;
    }
    
    .user-permission {
        margin: 0;
        font-size: 0.8125rem;
        color: var(--text-secondary);
    }
    
    .remove-user {
        background: none;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #ff5555;
        padding: 0.5rem;
        border-radius: 0.25rem;
    }
    
    .remove-user:hover {
        background-color: rgba(255, 85, 85, 0.1);
    }
    
    .no-users {
        color: var(--text-secondary);
        font-style: italic;
        font-size: 0.875rem;
    }
    
    .action-button.add-user {
        align-self: flex-start;
        background-color: var(--accent-color);
        border: none;
        border-radius: 0.375rem;
        color: white;
        font-weight: 500;
        padding: 0.5rem 1rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        cursor: pointer;
        transition: background-color 0.2s;
    }
    
    .action-button.add-user:hover {
        background-color: var(--accent-hover);
    }
    
    /* Loading state */
    .loading {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 3rem 0;
    }
    
    .spinner {
        width: 3rem;
        height: 3rem;
        border: 0.25rem solid rgba(var(--accent-color-rgb), 0.2);
        border-radius: 50%;
        border-top-color: var(--accent-color);
        animation: spin 1s linear infinite;
        margin-bottom: 1rem;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    /* Error state */
    .error-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 3rem 0;
        text-align: center;
    }
    
    .error-container .material-icons {
        font-size: 3rem;
        color: #ff5555;
        margin-bottom: 1rem;
    }
    
    .retry-button {
        background-color: var(--accent-color);
        border: none;
        border-radius: 0.375rem;
        color: white;
        font-weight: 500;
        padding: 0.5rem 1rem;
        margin-top: 1rem;
        cursor: pointer;
        transition: background-color 0.2s;
    }
    
    .retry-button:hover {
        background-color: var(--accent-hover);
    }
    
    /* Content header */
    .content-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.5rem;
    }
    
    .content-header h2 {
        font-size: 1.5rem;
        font-weight: 600;
        margin: 0;
    }
    
    .actions {
        display: flex;
        gap: 0.75rem;
    }
    
    .action-button {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        background-color: var(--bg-secondary);
        border: none;
        border-radius: 0.375rem;
        color: var(--text-primary);
        font-weight: 500;
        padding: 0.5rem 1rem;
        cursor: pointer;
        transition: background-color 0.2s;
    }
    
    .action-button.save {
        background-color: var(--accent-color);
        color: white;
    }
    
    .action-button.save:hover {
        background-color: var(--accent-hover);
    }
    
    .action-button.refresh:hover {
        background-color: var(--bg-tertiary);
    }
    
    /* Info popup */
    .info-popup {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1000;
    }
    
    .popup-content {
        background-color: var(--bg-primary);
        border-radius: 0.75rem;
        padding: 1.5rem;
        max-width: 30rem;
        width: 90%;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
    }
    
    .popup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
    }
    
    .popup-header h3 {
        margin: 0;
        font-size: 1.25rem;
        font-weight: 600;
    }
    
    .close-popup {
        background: none;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--text-secondary);
    }
    
    .close-popup:hover {
        color: var(--text-primary);
    }

    .authorized-users-container {
        display: flex;
        flex-direction: column;
        gap: 1.5rem;
    }

    .user-cards-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr));
        gap: 1rem;
    }

    .user-card {
        display: flex;
        align-items: center;
        gap: 1rem;
        background-color: var(--bg-tertiary);
        border-radius: 0.5rem;
        padding: 0.75rem 1rem;
        transition: transform 0.2s, box-shadow 0.2s;
    }

    .user-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }
    
    /* Responsive design */
    @media (max-width: 768px) {
        .settings-grid {
            grid-template-columns: 1fr;
        }

        .image-preview-wrapper {
            flex-direction: column;
            align-items: flex-start;
        }
        
        .user-cards-grid {
            grid-template-columns: 1fr;
        }
        
        .content-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 1rem;
        }
        
        .actions {
            width: 100%;
        }
        
        .action-button {
            flex: 1;
            justify-content: center;
        }
    }
    
    /* Main layout */
    .layout {
        display: flex;
        height: 100vh;
        overflow: hidden;
    }
    
    .dashboard {
        display: flex;
        flex: 1;
        overflow: hidden;
    }
    
    .content-area {
        flex: 1;
        padding: 2rem;
        overflow-y: auto;
    }
</style>