<script lang="ts">
    import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore, discordDataStore, client, TAServerAPIPort } from "$lib/stores";
    import { onMount, onDestroy } from "svelte";
    //@ts-ignore
    import { Match, Tournament, TAClient, Response_ResponseType, QualifierEvent, Map, Tournament_TournamentSettings } from 'moons-ta-client';
    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 { generateRandomHexColor } from "$lib/services/colours.js";
    import { v4 as uuidv4 } from "uuid";
    import Popup from "$lib/components/notifications/Popup.svelte";
    import { goto } from "$app/navigation";
    import { fetchMapsByLevelIds, type BeatSaverMap } from "$lib/services/beatsaver.js";

    export let data;

    interface CustomQualifiersType extends QualifierEvent {
        maps: BeatSaverMap[];
    }

    const tournamentGuid: string = data.tournamentGuid;
    let tournament: Tournament | undefined;
    let isLoading = false;
    let error: string | null = null;
    
    let qualifiers: CustomQualifiersType[] = [];
    
    let showQualifierPopup: boolean = false;
    let newQualifierName: string = "";
    let qualifierImageBuffer: Uint8Array | null = null;
    let qualifierImagePreview: string | null = null;
    
    let showInfoPopup: boolean = false;
    let infoPopupContent: string = "";

    let showDeleteWarning: boolean = false;
    let qualifierToDelete: string = "";
    
    let fileInput: HTMLInputElement;

    let hoveredMapIndex: number = -1;
    let hoveredQualIndex: number = -1;

    if ($authTokenStore) {
        const cleanToken = $authTokenStore.replace('Bearer ', '');
        client.setAuthToken(cleanToken);
    }
    
    function openInfoPopup(content: string) {
        infoPopupContent = content;
        showInfoPopup = true;
    }
    
    function closeInfoPopup() {
        showInfoPopup = false;
    }
    
    function openQualifierPopup() {
        newQualifierName = "";
        qualifierImageBuffer = null;
        qualifierImagePreview = null;
        showQualifierPopup = true;
    }
    
    function closeQualifierPopup() {
        showQualifierPopup = false;
    }
    
    function handleImageUpload() {
        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;
                if (result instanceof ArrayBuffer) {
                    qualifierImageBuffer = new Uint8Array(result);
                    const blob = new Blob([result as ArrayBuffer], { type: file.type });
                    qualifierImagePreview = URL.createObjectURL(blob);
                }
            };
            
            reader.readAsArrayBuffer(file);
        }
    }
    
    async function createQualifier() {
        const newQualifier: QualifierEvent = {
            guid: uuidv4(),
            name: newQualifierName,
            // image: qualifierImageBuffer || new Uint8Array(1),
            image: "",
            qualifierMaps: [],
            infoChannel: {
                id: "",
                name: ""
            },
            flags: 0,
            sort: 0
        };

        let createQualifierResponse = await client.createQualifierEvent(tournamentGuid, newQualifier.name, newQualifier.infoChannel!.id, [], 0, 0, qualifierImageBuffer || new Uint8Array(1));
        console.log("newQual", createQualifierResponse);
        
        qualifiers = [
            ...qualifiers,
            {
                ...(createQualifierResponse as any).details.createQualifierEvent.qualifier,
                maps: []
            }
        ];
        
        closeQualifierPopup();
    }
    
    function confirmDeleteQualifier(qualifierGuid: string) {
        qualifierToDelete = qualifierGuid;
        showDeleteWarning = true;
    }

    function closeDeleteWarning() {
        showDeleteWarning = false;
        qualifierToDelete = "";
    }
    
    async function deleteQualifier() {
        let removeQualifierResponse = await client.deleteQualifierEvent(tournamentGuid, qualifierToDelete);
        
        qualifiers = qualifiers.filter(qualifier => qualifier.guid !== qualifierToDelete);
        closeDeleteWarning();
    }

    function editQualifier(qualifierGuid: string) {
        goto(`/tournaments/${tournamentGuid}/qualifiers/${qualifierGuid}`);
    }

    async function fetchQualifiersData() {
        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)!;

            console.log("tournament", tournament)

            // Process all qualifiers in parallel and wait for all to complete
            const processedQualifiers = await Promise.all(
                tournament.qualifiers.map(async (qualifier) => {
                    const mapLevelIds = qualifier.qualifierMaps.map(map => map.gameplayParameters!.beatmap!.levelId);
                    const newMapDataArray = await fetchMapsByLevelIds(mapLevelIds);
                    
                    return {
                        ...qualifier,
                        maps: newMapDataArray
                    };
                })
            );

            // Assign the completed array to qualifiers
            qualifiers = processedQualifiers;

            console.log('quals', qualifiers);
            
        } catch (err) {
            console.error('Error fetching qualifiers data:', err);
            error = err instanceof Error ? err.message : 'An unknown error occurred';
        } finally {
            isLoading = false;
        }
    }

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

<div class="layout">
    <main class="dashboard">
        <SideMenu currentPage="qualifiers" tournamentName={tournament?.settings?.tournamentName} tournamnentGuid={tournamentGuid} />
        
        <div class="content-area">
            <div class="content-header">
                <h2>Qualifiers Management</h2>
                <div class="actions">
                    {#if !error && !isLoading}
                        <button class="action-button add" on:click={openQualifierPopup}>
                            <span class="material-icons">add</span>
                            Create Qualifier
                        </button>
                        <button class="action-button refresh" on:click={fetchQualifiersData}>
                            <span class="material-icons">refresh</span>
                            Refresh
                        </button>
                    {/if}
                </div>
            </div>
            
            <div class="qualifiers-header">
                <h3>Qualifiers</h3>
                <button class="info-button" on:click={() => openInfoPopup("Qualifiers are tournament rounds where players compete on specific maps to advance to the next stage.")}>
                    <span class="material-icons">info</span>
                </button>
            </div>
            
            {#if isLoading}
                <div class="loading">
                    <div class="spinner"></div>
                    <p>Loading qualifiers 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={fetchQualifiersData}>Retry</button>
                </div>
            {:else if qualifiers.length === 0}
                <div class="no-qualifiers">
                    <span class="material-icons">quiz</span>
                    <p>No qualifiers have been created yet</p>
                    <button class="action-button add" on:click={openQualifierPopup}>
                        <span class="material-icons">add</span>
                        Create First Qualifier
                    </button>
                </div>
            {:else}
                <div class="qualifiers-list">
                    {#each qualifiers as qualifier, qualIndex}
                        <div class="qualifier-card">
                            <div class="qualifier-header">
                                <img class="qualifier-image" src={qualifier.image && qualifier.image.length > 2 ? `https://${$TAServerUrl}:${$TAServerAPIPort}/api/file/${qualifier.image}` : '/talogo.png'} alt="{qualifier.name}" />
                                <div class="qualifier-info">
                                    <h4>{qualifier.name}</h4>
                                    <p class="maps-count">{qualifier.qualifierMaps.length} maps</p>
                                </div>
                                <div class="qualifier-actions">
                                    <button class="qualifier-action edit" title="Edit qualifier" on:click={() => editQualifier(qualifier.guid)}>
                                        <span class="material-icons">edit</span>
                                    </button>
                                    <button class="qualifier-action delete" title="Delete qualifier" on:click={() => confirmDeleteQualifier(qualifier.guid)}>
                                        <span class="material-icons">delete</span>
                                    </button>
                                </div>
                            </div>
                            
                            <div class="maps-grid">
                                {#each qualifier.maps as map, mapIndex}
                                    <!-- svelte-ignore a11y-no-static-element-interactions -->
                                    <div 
                                        class="map-card" 
                                        class:expanded={hoveredMapIndex === mapIndex && hoveredQualIndex === qualIndex}
                                        on:mouseenter={() => {hoveredMapIndex = mapIndex; hoveredQualIndex = qualIndex}}
                                        on:mouseleave={() => {hoveredMapIndex = -1; hoveredQualIndex = -1}}
                                    >
                                        <div class="map-image-container">
                                            <img class="map-image" src={map.versions[0].coverURL} alt={map.metadata.songName} />
                                        </div>
                                        <div class="map-info">
                                            <h5 class="map-name">{map.name}</h5>
                                            <p class="map-song">{map.metadata.songName}</p>
                                            <p class="map-artist">{map.metadata.songAuthorName}</p>
                                            <p class="map-mapper">Mapped by {map.metadata.levelAuthorName}</p>
                                        </div>
                                    </div>
                                {/each}
                            </div>
                        </div>
                    {/each}
                </div>
            {/if}
        </div>
    </main>
</div>

{#if showQualifierPopup}
    <div class="popup-overlay">
        <div class="popup-container">
            <div class="popup-header">
                <h3>Create New Qualifier</h3>
                <button class="close-button" on:click={closeQualifierPopup}>
                    <span class="material-icons">close</span>
                </button>
            </div>
            
            <div class="popup-content">
                <div class="form-group">
                    <label for="qualifier-name">Qualifier Name</label>
                    <input type="text" id="qualifier-name" class="form-input" bind:value={newQualifierName} placeholder="Enter qualifier name" required />
                </div>
                
                <div class="form-group">
                    <!-- svelte-ignore a11y-label-has-associated-control -->
                    <label>Qualifier Image (Optional)</label>
                    <div class="image-upload-container">
                        <div class="image-preview">
                            {#if qualifierImagePreview}
                                <img src={qualifierImagePreview} alt="Qualifier preview" />
                            <!-- svelte-ignore a11y-no-static-element-interactions -->
                            <!-- svelte-ignore a11y-click-events-have-key-events -->
                            {:else}
                                <!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
                                <!-- svelte-ignore a11y-click-events-have-key-events -->
                                <img on:click={handleImageUpload} src="/talogo.png" alt="Default logo" />
                                <!-- svelte-ignore a11y-click-events-have-key-events -->
                                <!-- svelte-ignore a11y-no-static-element-interactions -->
                                <div on:click={handleImageUpload} class="upload-overlay">
                                    <span class="material-icons">add_photo_alternate</span>
                                </div>
                            {/if}
                        </div>
                        <button class="action-button upload" on:click={handleImageUpload}>
                            <span class="material-icons">upload</span>
                            {qualifierImagePreview ? 'Change Image' : 'Upload Image'}
                        </button>
                        <input type="file" accept="image/*" style="display: none" bind:this={fileInput} on:change={onFileSelected} />
                    </div>
                </div>
                
                <div class="popup-actions">
                    <button class="action-button cancel" on:click={closeQualifierPopup}>Cancel</button>
                    <button class="action-button create" on:click={createQualifier} disabled={!newQualifierName}>Create Qualifier</button>
                </div>
            </div>
        </div>
    </div>
{/if}

{#if showDeleteWarning}
    <div class="popup-overlay">
        <div class="popup-container warning">
            <div class="popup-header">
                <h3>Delete Qualifier</h3>
                <button class="close-button" on:click={closeDeleteWarning}>
                    <span class="material-icons">close</span>
                </button>
            </div>
            <div class="popup-content">
                <div class="warning-content">
                    <span class="material-icons warning-icon">warning</span>
                    <p>Are you sure you want to delete this qualifier? This action cannot be undone.</p>
                </div>
                <div class="popup-actions">
                    <button class="action-button cancel" on:click={closeDeleteWarning}>Cancel</button>
                    <button class="action-button delete" on:click={deleteQualifier}>Delete</button>
                </div>
            </div>
        </div>
    </div>
{/if}

{#if showInfoPopup}
    <InfoPopup content={infoPopupContent} onClose={closeInfoPopup} />
{/if}

<style>
    .layout {
        display: flex;
        height: 100vh;
        overflow: hidden;
    }
    
    .dashboard {
        display: flex;
        flex: 1;
        overflow: hidden;
    }
    
    .content-area {
        flex: 1;
        padding: 2rem;
        overflow-y: auto;
    }
    
    .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.add, .action-button.create {
        background-color: var(--accent-color);
        color: white;
    }
    
    .action-button.add:hover, .action-button.create:hover {
        background-color: var(--accent-hover);
    }
    
    .action-button.delete {
        background-color: #ff5555;
        color: white;
    }
    
    .action-button.delete:hover {
        background-color: #ff3333;
    }
    
    .action-button.cancel {
        background-color: var(--bg-secondary);
    }
    
    .action-button.cancel:hover {
        background-color: var(--bg-tertiary);
    }
    
    .action-button.refresh:hover {
        background-color: var(--bg-tertiary);
    }
    
    .action-button.upload {
        background-color: var(--accent-color);
        color: white;
    }
    
    .action-button:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }
    
    .qualifiers-header {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        margin-bottom: 1rem;
    }
    
    .qualifiers-header h3 {
        font-size: 1.25rem;
        font-weight: 500;
        margin: 0;
    }
    
    .info-button {
        background: none;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--accent-color);
        padding: 0;
    }
    
    .info-button:hover {
        color: var(--accent-hover);
    }
    
    .qualifiers-list {
        display: flex;
        flex-direction: column;
        gap: 1.5rem;
    }
    
    .qualifier-card {
        background-color: var(--bg-secondary);
        border-radius: 0.5rem;
        padding: 1.5rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    
    .qualifier-header {
        display: flex;
        align-items: center;
        gap: 1rem;
        margin-bottom: 1rem;
    }
    
    .qualifier-image {
        width: 4rem;
        height: 4rem;
        border-radius: 0.5rem;
        object-fit: cover;
        background-color: var(--bg-tertiary);
    }
    
    .qualifier-info {
        flex: 1;
    }
    
    .qualifier-info h4 {
        font-size: 1.25rem;
        font-weight: 600;
        margin: 0 0 0.25rem 0;
    }
    
    .maps-count {
        color: var(--text-secondary);
        font-size: 0.875rem;
        margin: 0;
    }
    
    .qualifier-actions {
        display: flex;
        gap: 0.5rem;
    }
    
    .qualifier-action {
        background: none;
        border: none;
        width: 2rem;
        height: 2rem;
        border-radius: 0.25rem;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        color: var(--text-secondary);
    }
    
    .qualifier-action:hover {
        background-color: var(--bg-tertiary);
        color: var(--text-primary);
    }
    
    .qualifier-action.delete:hover {
        color: #ff5555;
    }
    
    .maps-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 0.75rem;
        perspective: 1000px;
        justify-content: flex-start;
        align-items: flex-start;
    }

    .map-card {
        background: var(--bg-tertiary);
        border-radius: 0.75rem;
        overflow: hidden;
        cursor: pointer;
        transition: all 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);
        transform-origin: center;
        position: relative;
        z-index: 1;
        width: 85px;
        height: 85px;
        transform: rotateY(-8deg) rotateX(3deg) scale(0.98);
        box-shadow: 
            0 4px 12px rgba(0, 0, 0, 0.1),
            0 2px 6px rgba(0, 0, 0, 0.08);
        border: 1px solid rgba(255, 255, 255, 0.1);
    }

    .map-card:hover {
        z-index: 15;
    }

    .map-card.expanded {
        width: 320px;
        height: 120px;
        transform: rotateY(0deg) rotateX(0deg) scale(1.02);
        box-shadow: 
            0 16px 48px rgba(0, 0, 0, 0.15),
            0 8px 24px rgba(0, 0, 0, 0.1),
            0 0 0 1px rgba(255, 255, 255, 0.15);
        background: linear-gradient(135deg, 
            var(--bg-tertiary) 0%, 
            color-mix(in srgb, var(--bg-tertiary) 90%, var(--accent-color) 10%) 100%);
    }

    .map-image-container {
        width: 100%;
        height: 100%;
        position: relative;
        overflow: hidden;
        border-radius: inherit;
    }

    .map-card:not(.expanded) .map-image-container {
        width: 85px;
        height: 85px;
    }

    .map-card.expanded .map-image-container {
        width: 85px;
        height: 85px;
        margin: 0.875rem;
        border-radius: 0.5rem;
        box-shadow: 
            0 6px 20px rgba(0, 0, 0, 0.2),
            0 0 0 2px rgba(255, 255, 255, 0.1);
        flex-shrink: 0;
    }

    .map-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: all 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);
        border-radius: inherit;
    }

    .map-info {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        padding: 0.875rem;
        background: linear-gradient(
            135deg,
            rgba(0, 0, 0, 0.75) 0%,
            rgba(0, 0, 0, 0.45) 50%,
            rgba(0, 0, 0, 0.85) 100%
        );
        color: white;
        opacity: 0;
        transform: translateX(100%);
        transition: all 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        z-index: 2;
        border-radius: inherit;
    }

    .map-card.expanded .map-info {
        opacity: 1;
        transform: translateX(103px);
        left: 0;
        right: 0;
        padding: 0.875rem 1rem 0.875rem 0.25rem;
        background: none;
        color: var(--text-primary);
        justify-content: center;
    }

    .map-name {
        font-size: 1rem;
        font-weight: 700;
        margin: 0 0 0.375rem 0;
        line-height: 1.2;
        text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6);
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .map-card.expanded .map-name {
        text-shadow: none;
        color: var(--text-primary);
        font-size: 1.05rem;
    }

    .map-song {
        font-size: 0.875rem;
        font-weight: 600;
        margin: 0 0 0.25rem 0;
        color: rgba(255, 255, 255, 0.95);
        line-height: 1.2;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .map-card.expanded .map-song {
        color: var(--text-primary);
    }

    .map-artist {
        font-size: 0.8rem;
        margin: 0 0 0.25rem 0;
        color: rgba(255, 255, 255, 0.85);
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .map-card.expanded .map-artist {
        color: var(--text-secondary);
    }

    .map-mapper {
        font-size: 0.75rem;
        margin: 0 0 0.5rem 0;
        color: rgba(255, 255, 255, 0.75);
        font-style: italic;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        /* overflow: hidden; */
    }

    .map-card.expanded .map-mapper {
        color: var(--text-secondary);
        opacity: 0.8;
    }

    .map-stats {
        display: flex;
        gap: 0.5rem;
        margin-top: auto;
        flex-wrap: wrap;
    }

    .duration {
        font-size: 0.7rem;
        font-weight: 600;
        padding: 0.25rem 0.5rem;
        border-radius: 12px;
        background: rgba(255, 255, 255, 0.25);
        backdrop-filter: blur(8px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        white-space: nowrap;
    }

    .map-card.expanded .duration {
        background: linear-gradient(135deg, var(--accent-color), color-mix(in srgb, var(--accent-color) 85%, white 15%));
        color: white;
        border: 1px solid rgba(255, 255, 255, 0.3);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    }

    /* Smooth staggering effect for nearby cards */
    .map-card:not(.expanded) {
        transition-delay: 0ms;
    }

    .map-card.expanded ~ .map-card {
        transform: translateX(15px) rotateY(-8deg) rotateX(3deg) scale(0.94);
        transition-delay: 50ms;
    }

    /* Responsive design improvements */
    @media (max-width: 768px) {
        .maps-grid {
            justify-content: center;
            gap: 0.5rem;
        }
        
        .map-card.expanded {
            width: 300px;
            height: 140px;
        }
        
        .map-card.expanded .map-image-container {
            width: 100px;
            height: 100px;
            margin: 1rem;
        }
        
        .map-card.expanded .map-info {
            transform: translateX(120px);
            padding-left: 0.5rem;
        }
    }

    @media (max-width: 520px) {
        .map-card {
            width: 75px;
            height: 75px;
        }
        
        .map-card.expanded {
            width: 100%;
            max-width: 300px;
            height: 130px;
        }
        
        .map-card.expanded .map-image-container {
            width: 85px;
            height: 85px;
            margin: 0.75rem;
        }
        
        .map-card.expanded .map-info {
            transform: translateX(95px);
            padding: 0.75rem 0.75rem 0.75rem 0.25rem;
        }
        
        .map-name {
            font-size: 0.9rem;
        }
        
        .map-card.expanded .map-name {
            font-size: 0.95rem;
        }
    }

    /* Enhanced focus states for accessibility */
    .map-card:focus-visible {
        outline: 2px solid var(--accent-color);
        outline-offset: 2px;
    }

    /* Subtle loading state if needed */
    .map-card.loading .map-image {
        background: linear-gradient(90deg, 
            var(--bg-secondary) 25%, 
            var(--bg-tertiary) 50%, 
            var(--bg-secondary) 75%);
        background-size: 200% 100%;
        animation: loading-shimmer 1.5s infinite;
    }

    @keyframes loading-shimmer {
        0% { background-position: -200% 0; }
        100% { background-position: 200% 0; }
    }
    
    .no-qualifiers {
        background-color: var(--bg-secondary);
        border-radius: 0.75rem;
        padding: 3rem 2rem;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        text-align: center;
    }
    
    .no-qualifiers .material-icons {
        font-size: 3rem;
        color: var(--text-secondary);
        margin-bottom: 1rem;
    }
    
    .no-qualifiers p {
        color: var(--text-secondary);
        margin-bottom: 1.5rem;
    }
    
    .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-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);
    }
    
    .popup-overlay {
        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-container {
        background-color: var(--bg-primary);
        border-radius: 0.75rem;
        width: 90%;
        max-width: 500px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
    }
    
    .popup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1.25rem 1.5rem;
        border-bottom: 1px solid var(--bg-secondary);
    }
    
    .popup-header h3 {
        margin: 0;
        font-size: 1.25rem;
        font-weight: 600;
    }
    
    .close-button {
        background: none;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--text-secondary);
        width: 2rem;
        height: 2rem;
        border-radius: 0.25rem;
    }
    
    .close-button:hover {
        background-color: var(--bg-secondary);
        color: var(--text-primary);
    }
    
    .popup-content {
        padding: 1.5rem;
    }
    
    .form-group {
        margin-bottom: 1.25rem;
    }
    
    .form-group label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 500;
        font-size: 0.9375rem;
    }
    
    .form-input {
        width: 100%;
        padding: 0.625rem 0.75rem;
        background-color: var(--bg-tertiary);
        border: none;
        border-radius: 0.375rem;
        color: var(--text-primary);
        font-size: 0.9375rem;
        font-family: inherit;
    }
    
    .form-input:focus {
        outline: 2px solid var(--accent-color);
    }
    
    .image-upload-container {
        display: flex;
        gap: 1rem;
        align-items: center;
    }
    
    .image-preview {
        width: 4rem;
        height: 4rem;
        border-radius: 0.375rem;
        overflow: hidden;
        background-color: var(--bg-tertiary);
        position: relative;
        cursor: pointer;
    }
    
    .image-preview img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    .upload-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: rgba(0, 0, 0, 0.3);
        color: white;
        cursor: pointer;
    }
    
    .popup-actions {
        display: flex;
        justify-content: flex-end;
        gap: 0.75rem;
        margin-top: 1.5rem;
    }
    
    .warning-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        text-align: center;
        gap: 1rem;
    }
    
    .warning-icon {
        font-size: 3rem;
        color: #ff5555;
    }
    
    @media (max-width: 768px) {
        .content-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 1rem;
        }
        
        .actions {
            width: 100%;
        }
        
        .action-button {
            flex: 1;
            justify-content: center;
        }
    }
</style>