{extends file="layout.tpl"}

{block name="content"}
<div class="container-fluid">
    <div class="row">
        {if $isAdmin}
        <!-- Sidebar z listą użytkowników -->
        <div class="col-lg-3 mb-4">
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0"><i class="bi bi-people me-2"></i>Użytkownicy</h6>
                </div>
                <div class="card-body p-0">
                    <div class="list-group list-group-flush notes-user-list">
                        <a href="{$baseUrl}/notes" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center{if !$viewUserId} active{/if}">
                            <span><i class="bi bi-person-fill me-2"></i>Moje notatki</span>
                        </a>
                        {foreach $users as $user}
                        {if $user.id != $currentUser.id}
                        <a href="{$baseUrl}/notes?user_id={$user.id}" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center{if $viewUserId == $user.id} active{/if}">
                            <span>
                                <i class="bi bi-person me-2"></i>{$user.username}
                                {if $user.role == 'admin'}<span class="badge bg-warning text-dark ms-1">Admin</span>{/if}
                            </span>
                        </a>
                        {/if}
                        {/foreach}
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Główna zawartość -->
        <div class="col-lg-9">
        {else}
        <div class="col-12">
        {/if}
            <!-- Header -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h4 class="mb-1">
                        {if $viewUser}
                        <i class="bi bi-journal-text me-2"></i>Notatki: {$viewUser.username}
                        {else}
                        <i class="bi bi-journal-text me-2"></i>Moje notatki
                        {/if}
                    </h4>
                    <p class="text-muted mb-0">Przechowuj swoje notatki i informacje</p>
                </div>
                <div id="saveStatus" class="text-muted small" style="display:none;">
                    <i class="bi bi-check-circle text-success me-1"></i>Zapisano
                </div>
            </div>

            <!-- Notes Card -->
            <div class="card">
                <div class="card-body">
                    <form method="post" action="{$baseUrl}/notes/save" id="notesForm">
                        <input type="hidden" name="csrf_token" value="{$csrfToken}">
                        {if $viewUserId}
                        <input type="hidden" name="user_id" value="{$viewUserId}">
                        {/if}
                        
                        <div class="mb-3">
                            <textarea name="content" 
                                      id="notesContent" 
                                      class="form-control notes-textarea" 
                                      rows="20" 
                                      placeholder="Wpisz swoje notatki tutaj...">{$notes}</textarea>
                        </div>

                        <div class="d-flex justify-content-between align-items-center">
                            <small class="text-muted">
                                <i class="bi bi-info-circle me-1"></i>
                                Notatki zapisują się automatycznie po 2 sekundach od ostatniej zmiany
                            </small>
                            <button type="submit" class="btn btn-primary" id="saveBtn">
                                <i class="bi bi-check-lg me-1"></i>Zapisz
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
{/block}

{block name="scripts"}
<script>
(function() {
    const form = document.getElementById('notesForm');
    const textarea = document.getElementById('notesContent');
    const saveBtn = document.getElementById('saveBtn');
    const saveStatus = document.getElementById('saveStatus');
    let saveTimeout = null;
    let isSaving = false;
    let lastSavedContent = textarea.value;

    // Autosave po 2 sekundach od ostatniej zmiany
    textarea.addEventListener('input', function() {
        if (saveTimeout) {
            clearTimeout(saveTimeout);
        }
        
        saveStatus.style.display = 'none';
        
        saveTimeout = setTimeout(function() {
            if (textarea.value !== lastSavedContent) {
                autoSave();
            }
        }, 2000);
    });

    // Zapisz przy opuszczaniu strony
    window.addEventListener('beforeunload', function(e) {
        if (textarea.value !== lastSavedContent && !isSaving) {
            e.preventDefault();
            e.returnValue = '';
        }
    });

    // Funkcja autosave
    async function autoSave() {
        if (isSaving) return;
        
        isSaving = true;
        saveBtn.disabled = true;
        saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Zapisuję...';
        
        try {
            const formData = new FormData(form);
            const response = await fetch(form.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });
            
            const result = await response.json();
            
            if (result.success) {
                lastSavedContent = textarea.value;
                saveStatus.style.display = 'block';
                setTimeout(function() {
                    saveStatus.style.display = 'none';
                }, 3000);
            }
        } catch (error) {
            console.error('Błąd zapisu:', error);
        } finally {
            isSaving = false;
            saveBtn.disabled = false;
            saveBtn.innerHTML = '<i class="bi bi-check-lg me-1"></i>Zapisz';
        }
    }

    // Obsługa formularza
    form.addEventListener('submit', function(e) {
        if (textarea.value === lastSavedContent) {
            e.preventDefault();
            saveStatus.style.display = 'block';
            return;
        }
        
        // Pozwól na normalny submit jeśli coś się zmieniło
    });
})();
</script>
{/block}

{block name="styles"}
<style>
.notes-textarea {
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 0.9rem;
    line-height: 1.6;
    resize: vertical;
    min-height: 400px;
}

.notes-user-list {
    max-height: 500px;
    overflow-y: auto;
}

.notes-user-list .list-group-item {
    background: transparent;
    border-color: var(--sidebar-border);
    color: var(--text-primary);
    padding: 0.6rem 1rem;
}

.notes-user-list .list-group-item:hover {
    background: rgba(255, 255, 255, 0.05);
}

.notes-user-list .list-group-item.active {
    background: var(--accent-primary);
    border-color: var(--accent-primary);
}
</style>
{/block}
