{% extends "base.html" %}

{% block title %}Zarządzanie Osobami - Norda Biznes Partner{% endblock %}

{% block extra_css %}
<style>
    .admin-header {
        margin-bottom: var(--spacing-xl);
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
    }

    .admin-header-content h1 {
        font-size: var(--font-size-3xl);
        color: var(--text-primary);
        margin: 0;
    }

    .admin-header-content p { margin: var(--spacing-xs) 0 0 0; }

    .btn-add {
        display: inline-flex;
        align-items: center;
        gap: var(--spacing-sm);
        padding: var(--spacing-sm) var(--spacing-lg);
        background: var(--primary);
        color: white;
        border: none;
        border-radius: var(--radius);
        font-size: var(--font-size-base);
        font-weight: 500;
        cursor: pointer;
        transition: var(--transition);
    }

    .btn-add:hover { opacity: 0.9; }
    .btn-add svg { width: 20px; height: 20px; }

    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: var(--spacing-lg);
        margin-bottom: var(--spacing-2xl);
    }

    .stat-card {
        background: var(--surface);
        padding: var(--spacing-lg);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow);
        text-align: center;
    }

    .stat-value {
        font-size: var(--font-size-3xl);
        font-weight: 700;
        color: var(--primary);
    }

    .stat-label {
        color: var(--text-secondary);
        font-size: var(--font-size-sm);
        margin-top: var(--spacing-xs);
    }

    .filters-row {
        display: flex;
        gap: var(--spacing-md);
        margin-bottom: var(--spacing-lg);
        flex-wrap: wrap;
        align-items: center;
    }

    .filter-group {
        display: flex;
        align-items: center;
        gap: var(--spacing-xs);
    }

    .filter-group label {
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
        font-weight: 500;
    }

    .filter-select, .filter-input {
        padding: var(--spacing-xs) var(--spacing-sm);
        border: 1px solid var(--border);
        border-radius: var(--radius);
        font-size: var(--font-size-sm);
        background: var(--surface);
    }

    .filter-select:focus, .filter-input:focus {
        outline: none;
        border-color: var(--primary);
    }

    .section {
        background: var(--surface);
        padding: var(--spacing-xl);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow);
        margin-bottom: var(--spacing-xl);
    }

    .section h2 {
        font-size: var(--font-size-xl);
        margin-bottom: var(--spacing-lg);
        color: var(--text-primary);
        border-bottom: 2px solid var(--border);
        padding-bottom: var(--spacing-sm);
    }

    .data-table {
        width: 100%;
        border-collapse: collapse;
    }

    .data-table th, .data-table td {
        padding: var(--spacing-md);
        text-align: left;
        border-bottom: 1px solid var(--border);
    }

    .data-table th {
        font-weight: 600;
        color: var(--text-secondary);
        font-size: var(--font-size-sm);
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .data-table tr:hover { background: var(--background); }

    .person-name { font-weight: 500; color: var(--text-primary); }

    .pesel-masked {
        font-family: monospace;
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
    }

    .roles-list {
        display: flex;
        flex-direction: column;
        gap: 4px;
    }

    .role-item {
        font-size: var(--font-size-sm);
    }

    .role-item .role-name {
        color: var(--text-primary);
    }

    .role-item .company-name {
        color: var(--text-secondary);
    }

    .badge {
        display: inline-block;
        padding: 2px 8px;
        border-radius: var(--radius-sm);
        font-size: var(--font-size-xs);
        font-weight: 500;
    }

    .badge-zarzad { background: #DBEAFE; color: #1D4ED8; }
    .badge-wspolnik { background: #D1FAE5; color: #065F46; }
    .badge-prokurent { background: #FEF3C7; color: #92400E; }

    .action-buttons {
        display: flex;
        gap: var(--spacing-xs);
        flex-wrap: wrap;
    }

    .btn-icon {
        width: 32px;
        height: 32px;
        padding: 0;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: var(--radius);
        border: 1px solid var(--border);
        background: var(--surface);
        cursor: pointer;
        transition: var(--transition);
    }

    .btn-icon:hover { background: var(--background); }
    .btn-icon svg { width: 16px; height: 16px; }
    .btn-icon.danger:hover { background: var(--error); border-color: var(--error); color: white; }

    .empty-state {
        text-align: center;
        padding: var(--spacing-2xl);
        color: var(--text-secondary);
    }

    /* Modal styles */
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        align-items: center;
        justify-content: center;
    }

    .modal.active { display: flex; }

    .modal-content {
        background: var(--surface);
        padding: var(--spacing-xl);
        border-radius: var(--radius-lg);
        max-width: 500px;
        width: 90%;
        box-shadow: var(--shadow-lg);
        max-height: 90vh;
        overflow-y: auto;
    }

    .modal-header {
        font-size: var(--font-size-xl);
        margin-bottom: var(--spacing-md);
        color: var(--text-primary);
    }

    .modal-body { margin-bottom: var(--spacing-lg); }

    .modal-footer {
        display: flex;
        justify-content: flex-end;
        gap: var(--spacing-sm);
    }

    .form-group { margin-bottom: var(--spacing-md); }

    .form-label {
        display: block;
        margin-bottom: var(--spacing-xs);
        color: var(--text-secondary);
        font-size: var(--font-size-sm);
        font-weight: 500;
    }

    .form-control {
        width: 100%;
        padding: var(--spacing-sm);
        border: 1px solid var(--border);
        border-radius: var(--radius);
        font-size: var(--font-size-base);
        font-family: inherit;
    }

    .form-control:focus {
        outline: none;
        border-color: var(--primary);
    }

    .btn {
        padding: var(--spacing-sm) var(--spacing-md);
        border: none;
        border-radius: var(--radius);
        font-size: var(--font-size-base);
        font-weight: 500;
        cursor: pointer;
        transition: var(--transition);
    }

    .btn-primary { background: var(--primary); color: white; }
    .btn-primary:hover { opacity: 0.9; }
    .btn-secondary { background: var(--background); color: var(--text-secondary); }
    .btn-secondary:hover { background: var(--border); }
    .btn-danger { background: #EF4444; color: white; }
    .btn-danger:hover { background: #DC2626; }

    /* Toast */
    .toast-container {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 2000;
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .toast {
        background: var(--surface);
        padding: var(--spacing-md) var(--spacing-lg);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-lg);
        display: flex;
        align-items: center;
        gap: var(--spacing-sm);
        min-width: 280px;
        max-width: 400px;
        animation: slideIn 0.3s ease;
        border-left: 4px solid var(--primary);
    }

    .toast.success { border-left-color: #10B981; }
    .toast.error { border-left-color: #EF4444; }

    .toast-icon { width: 24px; height: 24px; flex-shrink: 0; }
    .toast-icon.success { color: #10B981; }
    .toast-icon.error { color: #EF4444; }
    .toast-message { flex: 1; color: var(--text-primary); }

    .toast-close {
        background: none;
        border: none;
        color: var(--text-secondary);
        cursor: pointer;
        padding: 4px;
    }

    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }

    @keyframes slideOut {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }

    /* Confirm modal */
    .modal-icon {
        width: 48px;
        height: 48px;
        margin: 0 auto var(--spacing-md);
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
    }

    .modal-icon.danger { background: #FEE2E2; color: #EF4444; }
    .modal-icon svg { width: 24px; height: 24px; }

    .modal-title {
        font-size: var(--font-size-lg);
        font-weight: 600;
        text-align: center;
        margin-bottom: var(--spacing-sm);
    }

    .modal-description {
        text-align: center;
        color: var(--text-secondary);
        margin-bottom: var(--spacing-lg);
    }

    /* Companies list in modal */
    .companies-list {
        max-height: 300px;
        overflow-y: auto;
    }

    .company-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: var(--spacing-sm);
        border-bottom: 1px solid var(--border);
    }

    .company-item:last-child { border-bottom: none; }

    .company-item-info { flex: 1; }
    .company-item-name { font-weight: 500; }
    .company-item-role { font-size: var(--font-size-sm); color: var(--text-secondary); }

    .btn-remove-link {
        background: none;
        border: none;
        color: var(--error);
        cursor: pointer;
        padding: var(--spacing-xs);
    }

    .btn-remove-link:hover { opacity: 0.7; }

    .add-link-form {
        margin-top: var(--spacing-md);
        padding-top: var(--spacing-md);
        border-top: 1px solid var(--border);
    }

    @media (max-width: 768px) {
        .data-table { font-size: var(--font-size-sm); }
        .filters-row { flex-direction: column; align-items: stretch; }
    }
</style>
{% endblock %}

{% block content %}
<div class="admin-header">
    <div class="admin-header-content">
        <h1>Zarządzanie Osobami</h1>
        <p class="text-muted">Osoby powiązane z firmami (zarząd, wspólnicy, prokurenci)</p>
    </div>
    <button class="btn-add" onclick="openAddModal()">
        <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
            <path d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"/>
        </svg>
        Dodaj osobę
    </button>
</div>

<!-- Stats Grid -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-value">{{ total_people }}</div>
        <div class="stat-label">Wszystkich</div>
    </div>
    <div class="stat-card">
        <div class="stat-value" style="color: #3B82F6;">{{ with_companies }}</div>
        <div class="stat-label">Z powiązaniami</div>
    </div>
    <div class="stat-card">
        <div class="stat-value" style="color: #1D4ED8;">{{ zarzad_count }}</div>
        <div class="stat-label">W zarządach</div>
    </div>
    <div class="stat-card">
        <div class="stat-value" style="color: #065F46;">{{ wspolnik_count }}</div>
        <div class="stat-label">Wspólników</div>
    </div>
</div>

<!-- Filters -->
<form method="GET" class="filters-row">
    <div class="filter-group">
        <label>Rola:</label>
        <select name="role" class="filter-select" onchange="this.form.submit()">
            <option value="">Wszystkie</option>
            <option value="zarzad" {{ 'selected' if current_role == 'zarzad' else '' }}>Zarząd</option>
            <option value="wspolnik" {{ 'selected' if current_role == 'wspolnik' else '' }}>Wspólnicy</option>
            <option value="prokurent" {{ 'selected' if current_role == 'prokurent' else '' }}>Prokurenci</option>
        </select>
    </div>
    <div class="filter-group">
        <label>Szukaj:</label>
        <input type="text" name="q" class="filter-input" placeholder="Imię lub nazwisko..." value="{{ search_query }}" style="width: 200px;">
        <button type="submit" class="btn btn-primary" style="padding: var(--spacing-xs) var(--spacing-sm);">Szukaj</button>
    </div>
</form>

<!-- People Table -->
<div class="section">
    <h2>Osoby ({{ people|length }})</h2>

    {% if people %}
    <table class="data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Imiona i nazwisko</th>
                <th>PESEL</th>
                <th>Powiązania</th>
                <th>Akcje</th>
            </tr>
        </thead>
        <tbody>
            {% for person in people %}
            <tr data-person-id="{{ person.id }}">
                <td>{{ person.id }}</td>
                <td>
                    <span class="person-name">{{ person.full_name }}</span>
                </td>
                <td>
                    <span class="pesel-masked">{{ person.pesel_masked or '-' }}</span>
                </td>
                <td>
                    {% if person.roles %}
                    <div class="roles-list">
                        {% for role in person.roles[:3] %}
                        <div class="role-item">
                            <span class="badge badge-{{ role.role_category }}">{{ role.role_category }}</span>
                            <span class="role-name">{{ role.role }}</span>
                            <span class="company-name">@ {{ role.company_name }}</span>
                        </div>
                        {% endfor %}
                        {% if person.roles|length > 3 %}
                        <div class="role-item">
                            <span style="color: var(--text-secondary);">+{{ person.roles|length - 3 }} więcej...</span>
                        </div>
                        {% endif %}
                    </div>
                    {% else %}
                    <span style="color: var(--text-secondary);">Brak powiązań</span>
                    {% endif %}
                </td>
                <td>
                    <div class="action-buttons">
                        <button class="btn-icon" onclick="openEditModal({{ person.id }})" title="Edytuj">
                            <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                <path d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
                            </svg>
                        </button>
                        <button class="btn-icon" onclick="openCompaniesModal({{ person.id }}, '{{ person.full_name|e }}')" title="Powiązania z firmami">
                            <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                <path d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/>
                            </svg>
                        </button>
                        <button class="btn-icon danger" onclick="deletePerson({{ person.id }}, '{{ person.full_name|e }}')" title="Usuń">
                            <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                <path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                            </svg>
                        </button>
                    </div>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    {% else %}
    <div class="empty-state">
        <p>Brak osób spełniających kryteria</p>
    </div>
    {% endif %}
</div>

<!-- Add Person Modal -->
<div id="addModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">Dodaj nową osobę</div>
        <div class="modal-body">
            <div class="form-group">
                <label class="form-label">Imiona *</label>
                <input type="text" id="addImiona" class="form-control" placeholder="Jan Adam" required>
            </div>
            <div class="form-group">
                <label class="form-label">Nazwisko *</label>
                <input type="text" id="addNazwisko" class="form-control" placeholder="Kowalski" required>
            </div>
            <div class="form-group">
                <label class="form-label">PESEL (opcjonalnie)</label>
                <input type="text" id="addPesel" class="form-control" placeholder="12345678901" maxlength="11">
                <small style="color: var(--text-secondary);">11 cyfr. Pozostaw puste jeśli brak.</small>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeAddModal()">Anuluj</button>
            <button class="btn btn-primary" onclick="confirmAdd()">Utwórz osobę</button>
        </div>
    </div>
</div>

<!-- Edit Person Modal -->
<div id="editModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">Edytuj osobę</div>
        <div class="modal-body">
            <div class="form-group">
                <label class="form-label">Imiona *</label>
                <input type="text" id="editImiona" class="form-control" required>
            </div>
            <div class="form-group">
                <label class="form-label">Nazwisko *</label>
                <input type="text" id="editNazwisko" class="form-control" required>
            </div>
            <div class="form-group">
                <label class="form-label">PESEL (opcjonalnie)</label>
                <input type="text" id="editPesel" class="form-control" maxlength="11">
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeEditModal()">Anuluj</button>
            <button class="btn btn-primary" onclick="saveEdit()">Zapisz zmiany</button>
        </div>
    </div>
</div>

<!-- Companies Modal -->
<div id="companiesModal" class="modal">
    <div class="modal-content">
        <div class="modal-header" id="companiesModalTitle">Powiązania z firmami</div>
        <div class="modal-body">
            <div id="companiesList" class="companies-list">
                <div class="empty-state">Ładowanie...</div>
            </div>
            <div class="add-link-form" id="addLinkForm" style="display: none;">
                <h4 style="margin-bottom: var(--spacing-sm);">Dodaj powiązanie</h4>
                <div class="form-group">
                    <label class="form-label">Firma</label>
                    <input type="text" id="linkCompanySearch" class="form-control" placeholder="Szukaj firmy...">
                    <select id="linkCompanyId" class="form-control" style="margin-top: var(--spacing-xs);">
                        <option value="">-- Wybierz firmę --</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Rola</label>
                    <input type="text" id="linkRole" class="form-control" placeholder="np. PREZES ZARZĄDU">
                </div>
                <div class="form-group">
                    <label class="form-label">Kategoria roli</label>
                    <select id="linkRoleCategory" class="form-control">
                        <option value="zarzad">Zarząd</option>
                        <option value="wspolnik">Wspólnik</option>
                        <option value="prokurent">Prokurent</option>
                    </select>
                </div>
                <button class="btn btn-primary" onclick="confirmLink()">Dodaj powiązanie</button>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="toggleAddLinkForm()" id="toggleLinkBtn">Dodaj powiązanie</button>
            <button class="btn btn-secondary" onclick="closeCompaniesModal()">Zamknij</button>
        </div>
    </div>
</div>

<!-- Confirm Modal -->
<div id="confirmModal" class="modal">
    <div class="modal-content">
        <div id="confirmIcon" class="modal-icon danger">
            <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                <path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
            </svg>
        </div>
        <div id="confirmTitle" class="modal-title">Potwierdzenie</div>
        <div id="confirmDescription" class="modal-description"></div>
        <div class="modal-footer" style="justify-content: center;">
            <button class="btn btn-secondary" onclick="closeConfirmModal()">Anuluj</button>
            <button id="confirmAction" class="btn btn-danger">Usuń</button>
        </div>
    </div>
</div>

<!-- Toast Container -->
<div id="toastContainer" class="toast-container"></div>
{% endblock %}

{% block extra_js %}
    const csrfToken = '{{ csrf_token() }}';
    let editPersonId = null;
    let currentPersonId = null;
    let confirmCallback = null;

    function showToast(message, type = 'success') {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;

        const iconSvg = {
            success: '<path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>',
            error: '<path d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"/>'
        };

        toast.innerHTML = `
            <svg class="toast-icon ${type}" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                ${iconSvg[type] || iconSvg.success}
            </svg>
            <span class="toast-message">${message}</span>
            <button class="toast-close" onclick="this.parentElement.remove()">
                <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                    <path d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        `;

        container.appendChild(toast);
        setTimeout(() => {
            toast.style.animation = 'slideOut 0.3s ease forwards';
            setTimeout(() => toast.remove(), 300);
        }, 5000);
    }

    // Add Modal
    function openAddModal() {
        document.getElementById('addImiona').value = '';
        document.getElementById('addNazwisko').value = '';
        document.getElementById('addPesel').value = '';
        document.getElementById('addModal').classList.add('active');
    }

    function closeAddModal() {
        document.getElementById('addModal').classList.remove('active');
    }

    async function confirmAdd() {
        const imiona = document.getElementById('addImiona').value.trim();
        const nazwisko = document.getElementById('addNazwisko').value.trim();

        if (!imiona || !nazwisko) {
            showToast('Imiona i nazwisko są wymagane', 'error');
            return;
        }

        try {
            const response = await fetch('/admin/people/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({
                    imiona: imiona,
                    nazwisko: nazwisko,
                    pesel: document.getElementById('addPesel').value.trim() || null
                })
            });

            const data = await response.json();
            if (data.success) {
                closeAddModal();
                showToast(data.message, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast(data.error || 'Wystąpił błąd', 'error');
            }
        } catch (error) {
            showToast('Błąd połączenia', 'error');
        }
    }

    // Edit Modal
    async function openEditModal(personId) {
        editPersonId = personId;

        try {
            const response = await fetch(`/admin/people/${personId}`);
            const data = await response.json();

            if (data.success) {
                document.getElementById('editImiona').value = data.person.imiona || '';
                document.getElementById('editNazwisko').value = data.person.nazwisko || '';
                document.getElementById('editPesel').value = '';
                document.getElementById('editModal').classList.add('active');
            } else {
                showToast(data.error || 'Nie można pobrać danych', 'error');
            }
        } catch (error) {
            showToast('Błąd połączenia', 'error');
        }
    }

    function closeEditModal() {
        editPersonId = null;
        document.getElementById('editModal').classList.remove('active');
    }

    async function saveEdit() {
        if (!editPersonId) return;

        const imiona = document.getElementById('editImiona').value.trim();
        const nazwisko = document.getElementById('editNazwisko').value.trim();

        if (!imiona || !nazwisko) {
            showToast('Imiona i nazwisko są wymagane', 'error');
            return;
        }

        const payload = { imiona, nazwisko };
        const pesel = document.getElementById('editPesel').value.trim();
        if (pesel) payload.pesel = pesel;

        try {
            const response = await fetch(`/admin/people/${editPersonId}/update`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify(payload)
            });

            const data = await response.json();
            if (data.success) {
                closeEditModal();
                showToast(data.message, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast(data.error || 'Wystąpił błąd', 'error');
            }
        } catch (error) {
            showToast('Błąd połączenia', 'error');
        }
    }

    // Companies Modal
    async function openCompaniesModal(personId, personName) {
        currentPersonId = personId;
        document.getElementById('companiesModalTitle').textContent = `Powiązania - ${personName}`;
        document.getElementById('companiesList').innerHTML = '<div class="empty-state">Ładowanie...</div>';
        document.getElementById('addLinkForm').style.display = 'none';
        document.getElementById('toggleLinkBtn').textContent = 'Dodaj powiązanie';
        document.getElementById('companiesModal').classList.add('active');

        try {
            const response = await fetch(`/admin/people/${personId}/companies`);
            const data = await response.json();

            if (data.success) {
                if (data.companies.length === 0) {
                    document.getElementById('companiesList').innerHTML = '<div class="empty-state">Brak powiązań z firmami</div>';
                } else {
                    let html = '';
                    data.companies.forEach(c => {
                        html += `
                            <div class="company-item">
                                <div class="company-item-info">
                                    <div class="company-item-name">${c.company_name}</div>
                                    <div class="company-item-role">${c.role} (${c.role_category})${c.shares_percent ? ' - ' + c.shares_percent + '%' : ''}</div>
                                </div>
                                <button class="btn-remove-link" onclick="unlinkCompany(${personId}, ${c.company_id}, ${c.link_id})" title="Usuń powiązanie">
                                    <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" width="16" height="16">
                                        <path d="M6 18L18 6M6 6l12 12"/>
                                    </svg>
                                </button>
                            </div>
                        `;
                    });
                    document.getElementById('companiesList').innerHTML = html;
                }
            } else {
                document.getElementById('companiesList').innerHTML = '<div class="empty-state">Błąd pobierania danych</div>';
            }
        } catch (error) {
            document.getElementById('companiesList').innerHTML = '<div class="empty-state">Błąd połączenia</div>';
        }
    }

    function closeCompaniesModal() {
        currentPersonId = null;
        document.getElementById('companiesModal').classList.remove('active');
    }

    function toggleAddLinkForm() {
        const form = document.getElementById('addLinkForm');
        const btn = document.getElementById('toggleLinkBtn');
        if (form.style.display === 'none') {
            form.style.display = 'block';
            btn.textContent = 'Anuluj dodawanie';
            loadCompaniesForSelect();
        } else {
            form.style.display = 'none';
            btn.textContent = 'Dodaj powiązanie';
        }
    }

    async function loadCompaniesForSelect() {
        try {
            const response = await fetch('/admin/companies?status=active');
            const parser = new DOMParser();
            const doc = parser.parseFromString(await response.text(), 'text/html');
            const rows = doc.querySelectorAll('[data-company-id]');

            const select = document.getElementById('linkCompanyId');
            select.innerHTML = '<option value="">-- Wybierz firmę --</option>';
            rows.forEach(row => {
                const id = row.dataset.companyId;
                const name = row.querySelector('.company-name')?.textContent || `Firma ${id}`;
                select.innerHTML += `<option value="${id}">${name}</option>`;
            });
        } catch (error) {
            console.error('Error loading companies:', error);
        }
    }

    async function confirmLink() {
        if (!currentPersonId) return;

        const companyId = document.getElementById('linkCompanyId').value;
        const role = document.getElementById('linkRole').value.trim();
        const roleCategory = document.getElementById('linkRoleCategory').value;

        if (!companyId || !role) {
            showToast('Wybierz firmę i podaj rolę', 'error');
            return;
        }

        try {
            const response = await fetch(`/admin/people/${currentPersonId}/link-company`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({
                    company_id: parseInt(companyId),
                    role: role,
                    role_category: roleCategory
                })
            });

            const data = await response.json();
            if (data.success) {
                showToast(data.message, 'success');
                openCompaniesModal(currentPersonId, document.getElementById('companiesModalTitle').textContent.replace('Powiązania - ', ''));
            } else {
                showToast(data.error || 'Wystąpił błąd', 'error');
            }
        } catch (error) {
            showToast('Błąd połączenia', 'error');
        }
    }

    async function unlinkCompany(personId, companyId, linkId) {
        try {
            const response = await fetch(`/admin/people/${personId}/unlink-company/${companyId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({ link_id: linkId })
            });

            const data = await response.json();
            if (data.success) {
                showToast(data.message, 'success');
                openCompaniesModal(personId, document.getElementById('companiesModalTitle').textContent.replace('Powiązania - ', ''));
            } else {
                showToast(data.error || 'Wystąpił błąd', 'error');
            }
        } catch (error) {
            showToast('Błąd połączenia', 'error');
        }
    }

    // Delete Person
    function deletePerson(personId, personName) {
        document.getElementById('confirmTitle').textContent = 'Usuń osobę';
        document.getElementById('confirmDescription').textContent = `Czy na pewno chcesz usunąć osobę "${personName}"? Zostaną również usunięte wszystkie powiązania z firmami.`;
        confirmCallback = async () => {
            try {
                const response = await fetch(`/admin/people/${personId}/delete`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': csrfToken
                    }
                });

                const data = await response.json();
                if (data.success) {
                    showToast(data.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(data.error || 'Wystąpił błąd', 'error');
                }
            } catch (error) {
                showToast('Błąd połączenia', 'error');
            }
        };
        document.getElementById('confirmModal').classList.add('active');
    }

    function closeConfirmModal() {
        document.getElementById('confirmModal').classList.remove('active');
        confirmCallback = null;
    }

    document.getElementById('confirmAction').addEventListener('click', function() {
        if (confirmCallback) confirmCallback();
        closeConfirmModal();
    });
{% endblock %}
