<!DOCTYPE html>
<html lang="pl" data-bs-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{$pageTitle|default:'Panel'} - Playlist Manager</title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- Custom CSS -->
    <link href="{$baseUrl}/assets/css/style.css" rel="stylesheet">
    {block name="styles"}{/block}
</head>
<body>
    {if $currentUser}
    <!-- Sidebar -->
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <a href="{$baseUrl}/" class="sidebar-brand">
                <i class="bi bi-collection-play-fill"></i>
                <span>Playlist Panel</span>
            </a>
            <button class="sidebar-toggle d-lg-none" id="sidebarClose">
                <i class="bi bi-x-lg"></i>
            </button>
        </div>
        
        <nav class="sidebar-nav">
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a href="{$baseUrl}/" class="nav-link{if $pageTitle == 'Dashboard'} active{/if}">
                        <i class="bi bi-speedometer2"></i>
                        <span>Dashboard</span>
                    </a>
                </li>
                
                {if $isAdmin || $isReseller}
                <li class="nav-item">
                    <a href="{$baseUrl}/users" class="nav-link{if $pageTitle == 'Użytkownicy' || $pageTitle == 'Dodaj użytkownika' || $pageTitle == 'Edytuj użytkownika'} active{/if}">
                        <i class="bi bi-people"></i>
                        <span>Użytkownicy</span>
                    </a>
                </li>
                {/if}
                
                <li class="nav-item">
                    <a href="{$baseUrl}/devices" class="nav-link{if $pageTitle == 'Urządzenia' || $pageTitle == 'Dodaj urządzenie' || $pageTitle == 'Edytuj urządzenie'} active{/if}">
                        <i class="bi bi-tv"></i>
                        <span>Urządzenia</span>
                    </a>
                </li>
                
                <li class="nav-item">
                    <a href="{$baseUrl}/playlists" class="nav-link{if $pageTitle == 'Playlisty' || $pageTitle == 'Dodaj playlistę' || $pageTitle == 'Edytuj playlistę'} active{/if}">
                        <i class="bi bi-list-ul"></i>
                        <span>Playlisty</span>
                    </a>
                </li>
                
                <li class="nav-item">
                    <a href="{$baseUrl}/dns" class="nav-link{if $pageTitle == 'Zmiana DNS'} active{/if}">
                        <i class="bi bi-arrow-repeat"></i>
                        <span>Zmiana DNS</span>
                    </a>
                </li>
                
                <li class="nav-item">
                    <a href="{$baseUrl}/notes" class="nav-link{if $pageTitle == 'Notatki'} active{/if}">
                        <i class="bi bi-journal-text"></i>
                        <span>Notatki</span>
                    </a>
                </li>
                
                <li class="nav-item">
                    <a href="{$baseUrl}/xtream-check" class="nav-link{if $pageTitle == 'Xtream Check'} active{/if}">
                        <i class="bi bi-broadcast"></i>
                        <span>Xtream Check</span>
                    </a>
                </li>
                
                {if isset($externalLinks) && $externalLinks|@count > 0}
                <li class="nav-header">Linki</li>
                {foreach $externalLinks as $extLink}
                <li class="nav-item">
                    <a href="{$extLink.url}" class="nav-link" {if $extLink.open_new_tab}target="_blank" rel="noopener noreferrer"{/if}>
                        <i class="bi {$extLink.icon}"></i>
                        <span>{$extLink.name}</span>
                        {if $extLink.open_new_tab}<i class="bi bi-box-arrow-up-right ms-auto small opacity-50"></i>{/if}
                    </a>
                </li>
                {/foreach}
                {/if}
                
                {* Moje ustawienia - dla wszystkich użytkowników *}
                <li class="nav-item">
                    <a href="{$baseUrl}/settings/my" class="nav-link{if $pageTitle|strstr:'Moje ustawienia'} active{/if}">
                        <i class="bi bi-sliders2"></i>
                        <span>Moje ustawienia</span>
                    </a>
                </li>
                
                {if $isAdmin}
                <li class="nav-header">Ustawienia urządzeń</li>
                <li class="nav-item">
                    <a href="{$baseUrl}/settings/definitions" class="nav-link{if $pageTitle == 'Definicje ustawień'} active{/if}">
                        <i class="bi bi-sliders"></i>
                        <span>Definicje</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/settings/presets" class="nav-link{if $pageTitle == 'Zestawy ustawień'} active{/if}">
                        <i class="bi bi-collection"></i>
                        <span>Presety</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/settings/global" class="nav-link{if $pageTitle == 'Ustawienia globalne'} active{/if}">
                        <i class="bi bi-globe"></i>
                        <span>Globalne</span>
                    </a>
                </li>
                {/if}
                
                {if $isAdmin || $isReseller}
                <li class="nav-header">Administracja</li>
                <li class="nav-item">
                    <a href="{$baseUrl}/admin/sessions" class="nav-link{if $pageTitle == 'Aktywne sesje'} active{/if}">
                        <i class="bi bi-broadcast"></i>
                        <span>Aktywne sesje</span>
                    </a>
                </li>
                {/if}
                {if $isAdmin}
                <li class="nav-item">
                    <a href="{$baseUrl}/admin/logs" class="nav-link{if $pageTitle == 'Logi aplikacji'} active{/if}">
                        <i class="bi bi-journal-text"></i>
                        <span>Logi aplikacji</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/admin/logs/api" class="nav-link{if $pageTitle == 'Logi API'} active{/if}">
                        <i class="bi bi-cloud-arrow-down"></i>
                        <span>Logi API</span>
                    </a>
                </li>
                
                <li class="nav-header">Raporty</li>
                <li class="nav-item">
                    <a href="{$baseUrl}/reports/activity" class="nav-link{if $pageTitle == 'Raport aktywności'} active{/if}">
                        <i class="bi bi-graph-up"></i>
                        <span>Aktywność</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/reports/audit" class="nav-link{if $pageTitle == 'Historia zmian'} active{/if}">
                        <i class="bi bi-clock-history"></i>
                        <span>Historia zmian</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/reports/logins" class="nav-link{if $pageTitle == 'Historia logowań'} active{/if}">
                        <i class="bi bi-door-open"></i>
                        <span>Historia logowań</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/reports/export" class="nav-link{if $pageTitle == 'Eksport danych'} active{/if}">
                        <i class="bi bi-file-earmark-arrow-down"></i>
                        <span>Eksport CSV</span>
                    </a>
                </li>
                
                <li class="nav-header">Bezpieczeństwo</li>
                <li class="nav-item">
                    <a href="{$baseUrl}/security" class="nav-link{if $pageTitle == 'Bezpieczeństwo'} active{/if}">
                        <i class="bi bi-shield-check"></i>
                        <span>Dashboard</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/security/ip-rules" class="nav-link{if $pageTitle == 'Reguły IP'} active{/if}">
                        <i class="bi bi-shield-lock"></i>
                        <span>Reguły IP</span>
                    </a>
                </li>
                
                <li class="nav-header">System</li>
                <li class="nav-item">
                    <a href="{$baseUrl}/admin/settings" class="nav-link{if $pageTitle == 'Konfiguracja systemu'} active{/if}">
                        <i class="bi bi-gear"></i>
                        <span>Konfiguracja</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/admin/links" class="nav-link{if $pageTitle == 'Linki zewnętrzne'} active{/if}">
                        <i class="bi bi-link-45deg"></i>
                        <span>Linki zewnętrzne</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/admin/monitor" class="nav-link{if $pageTitle == 'Monitor serwera'} active{/if}">
                        <i class="bi bi-speedometer2"></i>
                        <span>Monitor serwera</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/admin/system-logs" class="nav-link{if $pageTitle == 'Logi systemowe'} active{/if}">
                        <i class="bi bi-terminal"></i>
                        <span>Logi systemowe</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/admin/cron" class="nav-link{if $pageTitle == 'Harmonogram zadań'} active{/if}">
                        <i class="bi bi-calendar-check"></i>
                        <span>Harmonogram</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/admin/tools" class="nav-link{if $pageTitle == 'Narzędzia'} active{/if}">
                        <i class="bi bi-tools"></i>
                        <span>Narzędzia</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/admin/backups" class="nav-link{if $pageTitle == 'Kopie zapasowe'} active{/if}">
                        <i class="bi bi-cloud-download"></i>
                        <span>Kopie zapasowe</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="{$baseUrl}/admin/updates" class="nav-link{if $pageTitle == 'Aktualizacje'} active{/if}">
                        <i class="bi bi-arrow-repeat"></i>
                        <span>Aktualizacje</span>
                    </a>
                </li>
                {/if}
            </ul>
        </nav>
        
        <div class="sidebar-footer">
            <a href="{$baseUrl}/profile" class="user-info text-decoration-none">
                <div class="user-avatar">
                    <i class="bi bi-person-circle"></i>
                </div>
                <div class="user-details">
                    <span class="user-name">{$currentUser.username}</span>
                    <span class="user-role">{if $isAdmin}Administrator{elseif $isReseller}Reseller{else}Użytkownik{/if}</span>
                </div>
            </a>
        </div>
    </aside>

    <!-- Main Content -->
    <main class="main-content">
        <!-- Top Navbar -->
        <nav class="top-navbar">
            <button class="sidebar-toggle d-lg-none" id="sidebarToggle">
                <i class="bi bi-list"></i>
            </button>
            
            <div class="navbar-title d-none d-md-block">
                {$pageTitle|default:'Dashboard'}
            </div>
            
            <div class="navbar-actions">
                <div class="dropdown">
                    <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <i class="bi bi-person-circle"></i>
                        <span class="d-none d-md-inline ms-1">{$currentUser.username}</span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li>
                            <a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#changePasswordModal">
                                <i class="bi bi-key me-2"></i>Zmień hasło
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <li>
                            <a class="dropdown-item text-danger" href="{$baseUrl}/logout">
                                <i class="bi bi-box-arrow-right me-2"></i>Wyloguj
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>

        <!-- Page Content -->
        <div class="page-content">
            {if $flash}
            <div class="alert alert-{$flash.type} alert-dismissible fade show" role="alert">
                {$flash.message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            {/if}

            {block name="content"}{/block}
        </div>
    </main>

    <!-- Change Password Modal -->
    <div class="modal fade" id="changePasswordModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form action="{$baseUrl}/change-password" method="post">
                    <input type="hidden" name="csrf_token" value="{$csrfToken}">
                    <div class="modal-header">
                        <h5 class="modal-title">Zmień hasło</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Aktualne hasło</label>
                            <input type="password" name="current_password" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Nowe hasło</label>
                            <input type="password" name="new_password" class="form-control" minlength="6" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Potwierdź nowe hasło</label>
                            <input type="password" name="confirm_password" class="form-control" minlength="6" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Anuluj</button>
                        <button type="submit" class="btn btn-primary">Zmień hasło</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    {else}
    {block name="content"}{/block}
    {/if}

    <!-- Global Notes Modal -->
    <div class="modal fade" id="globalNotesModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-sticky me-2"></i>Notatki: <span id="notesModalEntityName"></span>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <span class="text-muted">
                            Liczba notatek: <span id="notesModalCount" class="badge bg-secondary">0</span>
                        </span>
                        <button type="button" class="btn btn-primary btn-sm" id="addNoteFromModalBtn">
                            <i class="bi bi-plus-lg me-1"></i>Dodaj notatkę
                        </button>
                    </div>
                    <div id="notesModalList" class="notes-modal-list">
                        <div class="text-center py-4 text-muted">
                            <i class="bi bi-sticky d-block mb-2" style="font-size: 2rem;"></i>
                            Brak notatek
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Note Edit Modal -->
    <div class="modal fade" id="noteEditModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="noteEditModalTitle">Nowa notatka</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="editNoteId" value="">
                    <input type="hidden" id="editNoteEntityType" value="">
                    <input type="hidden" id="editNoteEntityId" value="">
                    
                    <div class="mb-3">
                        <label class="form-label">Tytuł (opcjonalnie)</label>
                        <input type="text" id="editNoteTitle" class="form-control" placeholder="Tytuł notatki">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Treść <span class="text-danger">*</span></label>
                        <textarea id="editNoteContent" class="form-control" rows="4" placeholder="Treść notatki..." required></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Kolor</label>
                        <div class="d-flex gap-2 flex-wrap" id="editNoteColors">
                            <button type="button" class="btn btn-sm note-color-btn active" data-color="default" style="background: #6c757d; width: 32px; height: 32px; border-radius: 50%; border: 2px solid transparent;"></button>
                            <button type="button" class="btn btn-sm note-color-btn" data-color="red" style="background: #dc3545; width: 32px; height: 32px; border-radius: 50%; border: 2px solid transparent;"></button>
                            <button type="button" class="btn btn-sm note-color-btn" data-color="orange" style="background: #fd7e14; width: 32px; height: 32px; border-radius: 50%; border: 2px solid transparent;"></button>
                            <button type="button" class="btn btn-sm note-color-btn" data-color="yellow" style="background: #ffc107; width: 32px; height: 32px; border-radius: 50%; border: 2px solid transparent;"></button>
                            <button type="button" class="btn btn-sm note-color-btn" data-color="green" style="background: #198754; width: 32px; height: 32px; border-radius: 50%; border: 2px solid transparent;"></button>
                            <button type="button" class="btn btn-sm note-color-btn" data-color="blue" style="background: #0d6efd; width: 32px; height: 32px; border-radius: 50%; border: 2px solid transparent;"></button>
                            <button type="button" class="btn btn-sm note-color-btn" data-color="purple" style="background: #6f42c1; width: 32px; height: 32px; border-radius: 50%; border: 2px solid transparent;"></button>
                            <button type="button" class="btn btn-sm note-color-btn" data-color="pink" style="background: #d63384; width: 32px; height: 32px; border-radius: 50%; border: 2px solid transparent;"></button>
                        </div>
                    </div>
                    
                    <div class="form-check">
                        <input type="checkbox" id="editNotePinned" class="form-check-input">
                        <label class="form-check-label" for="editNotePinned">Przypnij na górze</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Anuluj</button>
                    <button type="button" class="btn btn-primary" id="saveNoteEditBtn">Zapisz</button>
                </div>
            </div>
        </div>
    </div>

    <style>
    .notes-modal-list .note-item {
        padding: 12px 15px;
        border: 1px solid var(--border-color);
        border-radius: 8px;
        margin-bottom: 10px;
        position: relative;
        padding-left: 20px;
    }
    .notes-modal-list .note-item:last-child { margin-bottom: 0; }
    .notes-modal-list .note-item.pinned { background: rgba(var(--bs-primary-rgb), 0.08); }
    .notes-modal-list .note-color-bar {
        width: 5px;
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        border-radius: 8px 0 0 8px;
    }
    .notes-modal-list .note-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 8px;
    }
    .notes-modal-list .note-title { font-weight: 600; font-size: 0.95rem; }
    .notes-modal-list .note-content { font-size: 0.9rem; white-space: pre-wrap; word-break: break-word; margin-bottom: 8px; }
    .notes-modal-list .note-meta { font-size: 0.8rem; color: var(--text-muted); }
    .note-color-btn.active { border-color: #fff !important; box-shadow: 0 0 0 2px rgba(255,255,255,0.3); }
    .notes-badge { cursor: pointer; transition: transform 0.2s; }
    .notes-badge:hover { transform: scale(1.1); }
    </style>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <!-- Custom JS -->
    <script src="{$baseUrl}/assets/js/app.js"></script>
    
    <!-- Global Notes Functions -->
    <script>
    {literal}
    window.NotesManager = (function() {
        var baseUrl = '';
        var currentUserId = 0;
        var isAdmin = false;
        var currentEntityType = '';
        var currentEntityId = 0;
        var currentEntityName = '';
        var notesModal = null;
        var editModal = null;
        
        var colors = {
            default: '#6c757d', red: '#dc3545', orange: '#fd7e14', yellow: '#ffc107',
            green: '#198754', blue: '#0d6efd', purple: '#6f42c1', pink: '#d63384'
        };
        
        function init(url, userId, admin) {
            baseUrl = url;
            currentUserId = userId;
            isAdmin = admin;
            notesModal = new bootstrap.Modal(document.getElementById('globalNotesModal'));
            editModal = new bootstrap.Modal(document.getElementById('noteEditModal'));
            
            // Color selection
            document.querySelectorAll('#editNoteColors .note-color-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('#editNoteColors .note-color-btn').forEach(function(b) { b.classList.remove('active'); });
                    this.classList.add('active');
                });
            });
            
            // Add from modal button
            document.getElementById('addNoteFromModalBtn').addEventListener('click', function() {
                openEditModal(null);
            });
            
            // Save button
            document.getElementById('saveNoteEditBtn').addEventListener('click', saveNote);
        }
        
        function canEditNote(note) {
            return isAdmin || (note.user_id == currentUserId);
        }
        
        function openNotesModal(entityType, entityId, entityName) {
            currentEntityType = entityType;
            currentEntityId = entityId;
            currentEntityName = entityName;
            
            document.getElementById('notesModalEntityName').textContent = entityName;
            loadNotes();
            notesModal.show();
        }
        
        function loadNotes() {
            fetch(baseUrl + '/entity-notes/list?entity_type=' + currentEntityType + '&entity_id=' + currentEntityId)
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (data.success) {
                        renderNotes(data.notes);
                        document.getElementById('notesModalCount').textContent = data.count;
                    }
                });
        }
        
        function renderNotes(notes) {
            var list = document.getElementById('notesModalList');
            
            if (notes.length === 0) {
                list.innerHTML = '<div class="text-center py-4 text-muted"><i class="bi bi-sticky d-block mb-2" style="font-size: 2rem;"></i>Brak notatek</div>';
                return;
            }
            
            list.innerHTML = notes.map(function(note) {
                var canEdit = canEditNote(note);
                var actionButtons = '';
                
                if (canEdit) {
                    actionButtons = '<div class="btn-group btn-group-sm">' +
                        '<button class="btn btn-outline-secondary btn-pin" data-id="' + note.id + '" title="' + (note.is_pinned ? 'Odepnij' : 'Przypnij') + '">' +
                            '<i class="bi bi-pin' + (note.is_pinned ? '-fill' : '') + '"></i>' +
                        '</button>' +
                        '<button class="btn btn-outline-primary btn-edit" data-note=\'' + JSON.stringify(note).replace(/'/g, "&#39;") + '\' title="Edytuj">' +
                            '<i class="bi bi-pencil"></i>' +
                        '</button>' +
                        '<button class="btn btn-outline-danger btn-delete" data-id="' + note.id + '" title="Usuń">' +
                            '<i class="bi bi-trash"></i>' +
                        '</button>' +
                    '</div>';
                }
                
                return '<div class="note-item ' + (note.is_pinned ? 'pinned' : '') + '" data-id="' + note.id + '">' +
                    '<div class="note-color-bar" style="background: ' + (colors[note.color] || colors.default) + '"></div>' +
                    '<div class="note-header">' +
                        '<div>' +
                            (note.is_pinned ? '<i class="bi bi-pin-fill text-primary me-1"></i>' : '') +
                            (note.title ? '<span class="note-title">' + escapeHtml(note.title) + '</span>' : '<span class="note-title text-muted">Bez tytułu</span>') +
                        '</div>' +
                        actionButtons +
                    '</div>' +
                    '<div class="note-content">' + escapeHtml(note.content || note.note || '') + '</div>' +
                    '<div class="note-meta">' +
                        '<i class="bi bi-person me-1"></i>' + (note.username || 'System') + ' • ' +
                        '<i class="bi bi-clock me-1"></i>' + formatDate(note.updated_at || note.created_at) +
                    '</div>' +
                '</div>';
            }).join('');
            
            // Bind events
            list.querySelectorAll('.btn-pin').forEach(function(btn) {
                btn.addEventListener('click', function() { togglePin(this.dataset.id); });
            });
            list.querySelectorAll('.btn-edit').forEach(function(btn) {
                btn.addEventListener('click', function() { openEditModal(JSON.parse(this.dataset.note)); });
            });
            list.querySelectorAll('.btn-delete').forEach(function(btn) {
                btn.addEventListener('click', function() { deleteNote(this.dataset.id); });
            });
        }
        
        function openEditModal(note) {
            document.getElementById('editNoteId').value = note ? note.id : '';
            document.getElementById('editNoteEntityType').value = currentEntityType;
            document.getElementById('editNoteEntityId').value = currentEntityId;
            document.getElementById('editNoteTitle').value = note ? (note.title || '') : '';
            document.getElementById('editNoteContent').value = note ? (note.content || note.note || '') : '';
            document.getElementById('editNotePinned').checked = note ? note.is_pinned : false;
            
            document.querySelectorAll('#editNoteColors .note-color-btn').forEach(function(b) { b.classList.remove('active'); });
            var colorBtn = document.querySelector('#editNoteColors .note-color-btn[data-color="' + (note ? (note.color || 'default') : 'default') + '"]');
            if (colorBtn) colorBtn.classList.add('active');
            
            document.getElementById('noteEditModalTitle').textContent = note ? 'Edytuj notatkę' : 'Nowa notatka';
            editModal.show();
        }
        
        function saveNote() {
            var noteId = document.getElementById('editNoteId').value;
            var content = document.getElementById('editNoteContent').value.trim();
            
            if (!content) {
                Swal.fire({ icon: 'error', title: 'Błąd', text: 'Treść notatki jest wymagana', background: '#1a1d21', color: '#e1e1e1' });
                return;
            }
            
            var formData = new FormData();
            formData.append('entity_type', document.getElementById('editNoteEntityType').value);
            formData.append('entity_id', document.getElementById('editNoteEntityId').value);
            formData.append('title', document.getElementById('editNoteTitle').value);
            formData.append('content', content);
            formData.append('color', document.querySelector('#editNoteColors .note-color-btn.active').dataset.color);
            formData.append('is_pinned', document.getElementById('editNotePinned').checked ? 1 : 0);
            
            if (noteId) formData.append('id', noteId);
            
            var url = noteId ? baseUrl + '/entity-notes/update' : baseUrl + '/entity-notes/add';
            
            fetch(url, { method: 'POST', body: formData })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (data.success) {
                        editModal.hide();
                        loadNotes();
                        updateBadge();
                    } else {
                        Swal.fire({ icon: 'error', title: 'Błąd', text: data.error || 'Wystąpił błąd', background: '#1a1d21', color: '#e1e1e1' });
                    }
                });
        }
        
        function togglePin(noteId) {
            var formData = new FormData();
            formData.append('id', noteId);
            
            fetch(baseUrl + '/entity-notes/toggle-pin', { method: 'POST', body: formData })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (data.success) loadNotes();
                });
        }
        
        function deleteNote(noteId) {
            Swal.fire({
                title: 'Usunąć notatkę?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Usuń',
                cancelButtonText: 'Anuluj',
                confirmButtonColor: '#dc3545',
                background: '#1a1d21',
                color: '#e1e1e1'
            }).then(function(result) {
                if (result.isConfirmed) {
                    var formData = new FormData();
                    formData.append('id', noteId);
                    
                    fetch(baseUrl + '/entity-notes/delete', { method: 'POST', body: formData })
                        .then(function(r) { return r.json(); })
                        .then(function(data) {
                            if (data.success) {
                                loadNotes();
                                updateBadge();
                            }
                        });
                }
            });
        }
        
        function updateBadge() {
            var badge = document.querySelector('.notes-badge[data-entity-type="' + currentEntityType + '"][data-entity-id="' + currentEntityId + '"]');
            if (badge) {
                fetch(baseUrl + '/entity-notes/list?entity_type=' + currentEntityType + '&entity_id=' + currentEntityId)
                    .then(function(r) { return r.json(); })
                    .then(function(data) {
                        if (data.success) {
                            badge.querySelector('.notes-count').textContent = data.count;
                            badge.style.display = data.count > 0 ? 'inline-flex' : 'none';
                        }
                    });
            }
        }
        
        function quickAdd(entityType, entityId, entityName) {
            currentEntityType = entityType;
            currentEntityId = entityId;
            currentEntityName = entityName;
            openEditModal(null);
        }
        
        function escapeHtml(text) {
            if (!text) return '';
            var div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        function formatDate(dateStr) {
            if (!dateStr) return '';
            var date = new Date(dateStr);
            return date.toLocaleDateString('pl-PL') + ' ' + date.toLocaleTimeString('pl-PL', {hour: '2-digit', minute: '2-digit'});
        }
        
        return {
            init: init,
            open: openNotesModal,
            quickAdd: quickAdd
        };
    })();
    {/literal}
    
    document.addEventListener('DOMContentLoaded', function() {
        NotesManager.init('{$baseUrl}', {$currentUser.id|default:0}, {if $isAdmin}true{else}false{/if});
    });
    </script>
    
    {block name="scripts"}{/block}
</body>
</html>
