@extends('layouts.app')
@section('title', 'Enterprise Kanban Board')

@push('styles')
<link rel="stylesheet" href="{{ asset('assets/css/dashboard-final.css') }}">
<style>
    .kanban-container {
        display: flex;
        gap: 20px;
        overflow-x: auto;
        padding-bottom: 24px;
        min-height: calc(100vh - 280px);
    }
    .kanban-column {
        flex: 0 0 340px;
        background: rgba(255, 255, 255, 0.02);
        border: 1px solid var(--border-color);
        border-radius: 24px;
        display: flex;
        flex-direction: column;
        padding: 16px;
        transition: all 0.3s ease;
    }
    .kanban-tasks {
        flex-grow: 1;
        display: flex;
        flex-direction: column;
        gap: 12px;
        min-height: 100px;
    }
    .task-card {
        background: var(--bg-card);
        border: 1px solid var(--border-color);
        border-radius: 16px;
        padding: 16px;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    .task-card:hover {
        border-color: var(--accent-soft);
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(0,0,0,0.2);
    }
    
    /* Enterprise Modal Styles */
    .enterprise-modal {
        position: fixed;
        inset: 0;
        z-index: 2000;
        display: none;
        align-items: center;
        justify-content: center;
        padding: 40px;
    }
    .enterprise-modal.open { display: flex; }
    .modal-overlay {
        position: absolute;
        inset: 0;
        background: rgba(0,0,0,0.8);
        backdrop-filter: blur(10px);
    }
    .modal-container {
        position: relative;
        background: var(--bg-dark);
        border: 1px solid var(--border-color);
        border-radius: 24px;
        width: 100%;
        max-width: 1000px;
        max-height: 90vh;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
    }
    .modal-header {
        padding: 24px 32px;
        border-bottom: 1px solid var(--border-color);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .modal-body {
        padding: 32px;
        overflow-y: auto;
        display: grid;
        grid-template-columns: 1fr 300px;
        gap: 32px;
    }
</style>
@endpush

@section('content')

@include('components.page-header', [
    'title' => 'Structural Kanban Command',
    'description' => 'Enterprise workforce task governance with real-time status intelligence and assignment oversight.',
    'breadcrumbs' => ['Home' => route('admin.dashboard'), 'Kanban' => '#'],
    'actions' => '<button onclick="openCreateModal()" class="final-btn final-btn-primary"><i class="bi bi-plus-lg"></i> Architect Task</button>'
])

<div class="final-card" style="margin-bottom: 24px;">
    <div style="display: flex; flex-wrap: wrap; gap: 16px; align-items: center;">
        <div class="relative" style="width: 250px;">
            <i class="bi bi-search absolute left-4 top-1/2 -translate-y-1/2 text-[var(--text-secondary)]"></i>
            <input type="text" id="taskSearch" placeholder="Search task ID/Name..." class="final-select" style="padding-left: 40px; width: 100%;">
        </div>
        <select class="final-select" style="width: 200px;" onchange="window.location.search = 'project_id=' + this.value">
            <option value="">All Projects</option>
            @foreach($projects as $p) <option value="{{ $p->id }}" @selected(request('project_id') == $p->id)>{{ $p->name }}</option> @endforeach
        </select>
        <select class="final-select" style="width: 200px;" onchange="updateFilter('employee_id', this.value)">
            <option value="">All Assignees</option>
            @foreach($employees as $e) <option value="{{ $e->id }}" @selected(request('employee_id') == $e->id)>{{ $e->name }}</option> @endforeach
        </select>
        <div style="margin-left: auto; display: flex; gap: 8px;">
            <a href="{{ route('tasks.index') }}" class="final-btn final-btn-secondary" style="padding: 8px 12px;"><i class="bi bi-list-task"></i></a>
            <a href="{{ route('tasks.kanban') }}" class="final-btn final-btn-primary" style="padding: 8px 12px;"><i class="bi bi-kanban"></i></a>
            <a href="{{ route('tasks.timeline') }}" class="final-btn final-btn-secondary" style="padding: 8px 12px;"><i class="bi bi-calendar-range"></i></a>
        </div>
    </div>
</div>

<div class="kanban-container scrollbar-modern">
    @foreach($statuses as $status)
    <div class="kanban-column">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding: 0 8px;">
            <div style="display: flex; align-items: center; gap: 10px;">
                <span style="width: 8px; height: 8px; border-radius: 50%; background: var(--accent-color);"></span>
                <h3 style="font-size: 11px; font-weight: 900; text-transform: uppercase; letter-spacing: 0.1em; color: var(--text-primary);">{{ $status->name }}</h3>
                <span style="font-size: 10px; font-weight: 800; color: var(--text-secondary); background: rgba(255,255,255,0.05); padding: 2px 8px; border-radius: 100px;">
                    {{ $tasksByStatus->get($status->id)?->count() ?? 0 }}
                </span>
            </div>
            <button class="final-secondary-text"><i class="bi bi-plus-circle"></i></button>
        </div>

        <div class="kanban-tasks" data-status-id="{{ $status->id }}">
            @foreach($tasksByStatus->get($status->id, []) as $task)
            <div class="task-card" data-task-id="{{ $task->id }}" onclick="editTask({{ $task->id }})">
                <div style="display: flex; justify-content: space-between; margin-bottom: 12px;">
                    <span class="final-badge {{ $task->priority == 'critical' ? 'badge-low' : 'badge-email' }}" style="font-size: 8px; padding: 2px 8px;">{{ strtoupper($task->priority) }}</span>
                    @if($task->hasActiveTimer())
                        <span class="final-badge badge-whatsapp" style="font-size: 8px; animation: pulse 2s infinite;"><i class="bi bi-stopwatch"></i> ACTIVE</span>
                    @endif
                </div>

                <h4 style="font-size: 14px; font-weight: 700; color: var(--text-primary); margin-bottom: 8px; line-height: 1.4;">{{ $task->title }}</h4>
                <div style="font-size: 10px; color: var(--text-secondary); margin-bottom: 16px; display: flex; align-items: center; gap: 4px;">
                    <i class="bi bi-folder2-open"></i> {{ $task->project->name }}
                </div>

                <div style="margin-bottom: 12px;">
                    <div style="display: flex; justify-content: space-between; margin-bottom: 6px;">
                        <span style="font-size: 9px; font-weight: 800; color: var(--text-secondary);">SUBTASKS</span>
                        <span style="font-size: 9px; font-weight: 800; color: var(--accent-color);">
                            @php $completedSub = $task->subtasks->where('task_status_id', 3)->count(); @endphp
                            {{ $completedSub }}/{{ $task->subtasks->count() }}
                        </span>
                    </div>
                    <div class="final-progress-bg" style="height: 4px;">
                        <div class="final-progress-fill" style="width: {{ $task->progress_percent }}%"></div>
                    </div>
                </div>

                <div style="display: flex; justify-content: space-between; align-items: center; padding-top: 12px; border-top: 1px solid var(--border-color);">
                    <div style="display: flex; -space-x: 6px;">
                        @foreach($task->assignees as $assignee)
                            <div class="final-avatar" style="width: 24px; height: 24px; font-size: 9px; border: 2px solid var(--bg-card);" title="{{ $assignee->name }}">
                                {{ substr($assignee->name, 0, 1) }}
                            </div>
                        @endforeach
                    </div>
                    <div style="font-size: 10px; font-weight: 800; color: var(--text-secondary);">
                        <i class="bi bi-hourglass-split"></i> {{ round($task->timeLogs->sum('total_seconds') / 3600, 1) }}h
                    </div>
                </div>
            </div>
            @endforeach
        </div>
    </div>
    @endforeach
</div>

<!-- Enterprise Task Modal -->
<div class="enterprise-modal" id="taskModal">
    <div class="modal-overlay" onclick="closeModal()"></div>
    <div class="modal-container">
        <div class="modal-header">
            <div style="display: flex; align-items: center; gap: 16px;">
                <span id="modalPriority" class="final-badge"></span>
                <h2 id="modalTaskTitleHeader" style="font-size: 18px; font-weight: 900; color: var(--text-primary);">Edit Task Module</h2>
            </div>
            <div style="display: flex; gap: 12px;">
                <button id="modalStatusBtn" class="final-btn final-btn-secondary" style="font-size: 11px;"></button>
                <button onclick="closeModal()" class="final-btn final-btn-secondary" style="padding: 8px;"><i class="bi bi-x-lg"></i></button>
            </div>
        </div>
        <form id="taskForm" onsubmit="saveTask(event)" class="modal-body scrollbar-modern">
            <input type="hidden" id="taskId" name="id">
            
            <div class="main-column">
                <div style="margin-bottom: 32px;">
                    <label class="final-stat-label">Task Identifier & Title</label>
                    <input type="text" id="taskTitle" name="title" class="final-input" style="font-size: 20px; font-weight: 800; margin-top: 8px;" required>
                </div>

                <div style="margin-bottom: 32px;">
                    <label class="final-stat-label">Intelligence Specification (Description)</label>
                    <textarea id="taskDescription" name="description" class="final-textarea" style="height: 150px; margin-top: 8px;"></textarea>
                </div>

                <div style="margin-bottom: 32px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                        <label class="final-stat-label">Subtask Architect (Checklist)</label>
                        <button type="button" onclick="addSubtask()" class="final-btn final-btn-secondary" style="padding: 4px 10px; font-size: 10px;"><i class="bi bi-plus-lg"></i> Add Step</button>
                    </div>
                    <div id="subtaskList" style="display: flex; flex-direction: column; gap: 10px;"></div>
                </div>

                <div>
                    <label class="final-stat-label">Collaborative Intelligence (Comments)</label>
                    <div id="commentList" style="margin-top: 16px; display: flex; flex-direction: column; gap: 12px; margin-bottom: 24px;"></div>
                    <div style="display: flex; gap: 12px;">
                        <input type="text" id="newComment" placeholder="Contribute to this intelligence..." class="final-input" style="flex-grow: 1;">
                        <button type="button" onclick="postComment()" class="final-btn final-btn-primary"><i class="bi bi-send"></i></button>
                    </div>
                </div>
            </div>

            <div class="side-column">
                <!-- Timer Control Section -->
                <div id="timerControl" class="final-card" style="background: rgba(181, 255, 107, 0.05); border-color: var(--accent-soft); padding: 20px; border-radius: 16px; margin-bottom: 24px; display: none;">
                    <label class="final-stat-label" style="color: var(--accent-color);">ACTIVE TIME TRACKING</label>
                    <div id="timerDisplay" style="font-size: 24px; font-weight: 900; color: var(--text-primary); margin: 12px 0;">00:00:00</div>
                    <div style="display: flex; gap: 10px;">
                        <button type="button" id="timerActionBtn" onclick="toggleTimer()" class="final-btn final-btn-primary" style="flex-grow: 1; justify-content: center;"></button>
                        <button type="button" id="stopTimerBtn" onclick="stopTimer()" class="final-btn final-btn-secondary" style="padding: 8px 12px;"><i class="bi bi-stop-fill"></i></button>
                    </div>
                </div>
                <div id="noTimerControl" style="margin-bottom: 24px;">
                    <button type="button" onclick="startTimer()" class="final-btn final-btn-primary" style="width: 100%; justify-content: center; background: rgba(255,255,255,0.05); border-color: var(--border-color); color: var(--text-primary);">
                        <i class="bi bi-play-fill"></i> Initiate Time Tracking
                    </button>
                </div>

                <div class="final-card" style="background: rgba(255,255,255,0.02); padding: 20px; border-radius: 16px;">
                    <div style="margin-bottom: 20px;">
                        <label class="final-stat-label">Governance Status</label>
                        <select id="taskStatus" name="task_status_id" class="final-select" style="margin-top: 8px;"></select>
                    </div>
                    <div style="margin-bottom: 20px;">
                        <label class="final-stat-label">Priority Tier</label>
                        <select id="taskPriority" name="priority" class="final-select" style="margin-top: 8px;">
                            <option value="low">Low</option>
                            <option value="medium">Medium</option>
                            <option value="high">High</option>
                            <option value="critical">Critical</option>
                        </select>
                    </div>
                    <div style="margin-bottom: 20px;">
                        <label class="final-stat-label">Delivery Deadline</label>
                        <input type="date" id="taskDeadline" name="deadline" class="final-input" style="margin-top: 8px;">
                    </div>
                    <div style="margin-bottom: 20px;">
                        <label class="final-stat-label">Visibility Logic</label>
                        <select id="taskVisibility" name="visibility" class="final-select" style="margin-top: 8px;">
                            <option value="public">Public (Organizational)</option>
                            <option value="department">Department Restricted</option>
                            <option value="assigned">Assigned Stakeholders Only</option>
                        </select>
                    </div>
                    <div style="margin-bottom: 20px;">
                        <label class="final-stat-label">Estimated Intelligence (Hrs)</label>
                        <input type="number" id="taskEstimate" name="estimated_hours" class="final-input" style="margin-top: 8px;">
                    </div>
                    <button type="submit" id="saveBtn" class="final-btn final-btn-primary" style="width: 100%; justify-content: center;">
                        <i class="bi bi-save"></i> Synchronize Changes
                    </button>
                </div>

                <div style="margin-top: 24px;">
                    <label class="final-stat-label">Assigned Engineers</label>
                    <div id="assignedList" style="display: flex; flex-wrap: wrap; gap: 6px; margin-top: 12px; margin-bottom: 12px;"></div>
                    <select name="assignee_ids[]" id="assigneeSelect" class="final-select" multiple style="height: 100px; font-size: 11px;">
                        @foreach($employees as $e) <option value="{{ $e->id }}">{{ $e->name }}</option> @endforeach
                    </select>
                </div>

                <div style="margin-top: 24px;">
                    <label class="final-stat-label">Subscribed Watchers</label>
                    <div id="watcherList" style="display: flex; flex-wrap: wrap; gap: 6px; margin-top: 12px; margin-bottom: 12px;"></div>
                    <select name="watcher_ids[]" id="watcherSelect" class="final-select" multiple style="height: 100px; font-size: 11px;">
                        @foreach($employees as $e) <option value="{{ $e->id }}">{{ $e->name }}</option> @endforeach
                    </select>
                </div>
            </div>
        </form>
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
    function updateFilter(key, val) {
        const url = new URL(window.location.href);
        if (val) url.searchParams.set(key, val);
        else url.searchParams.delete(key);
        window.location.href = url.toString();
    }

    // Kanban DnD
    document.querySelectorAll('.kanban-tasks').forEach(column => {
        new Sortable(column, {
            group: 'kanban', animation: 200, ghostClass: 'opacity-40',
            onEnd: (evt) => {
                const taskId = evt.item.dataset.taskId;
                const newStatusId = evt.to.dataset.statusId;
                const oldStatusId = evt.from.dataset.statusId;

                if (newStatusId === oldStatusId) return;

                fetch(`/tasks/${taskId}/status`, {
                    method: 'PATCH', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
                    body: JSON.stringify({ task_status_id: newStatusId })
                })
                .then(res => res.json())
                .then(data => {
                    if (!data.success) {
                        // Revert if backend says no
                        evt.from.appendChild(evt.item);
                        alert("Structural synchronization failed. Reverting placement.");
                    }
                })
                .catch(() => {
                    // Revert if network fails
                    evt.from.appendChild(evt.item);
                    alert("Network integrity compromised. Synchronize manually.");
                });
            }
        });
    });

    // Modal Logic
    const modal = document.getElementById('taskModal');
    function closeModal() { modal.classList.remove('open'); }
    
    function editTask(id) {
        modal.classList.add('open');
        // Show loading state if needed
        fetch(`/tasks/${id}`, { headers: { 'Accept': 'application/json' } })
            .then(res => res.json())
            .then(task => {
                if (!task) return;

                document.getElementById('taskId').value = task.id || '';
                document.getElementById('taskTitle').value = task.title || '';
                document.getElementById('taskDescription').value = task.description || '';
                document.getElementById('taskDeadline').value = task.deadline || '';
                document.getElementById('taskEstimate').value = task.estimated_hours || 0;
                document.getElementById('taskVisibility').value = task.visibility || 'public';
                document.getElementById('taskPriority').value = task.priority || 'medium';
                document.getElementById('modalTaskTitleHeader').innerText = task.title ? `Task: ${task.title}` : 'Edit Task Module';
                
                // Populate Statuses
                const statusSelect = document.getElementById('taskStatus');
                statusSelect.innerHTML = '';
                @foreach($statuses as $s)
                    statusSelect.innerHTML += `<option value="{{ $s->id }}" ${task.status && task.status.id == {{ $s->id }} ? 'selected' : ''}>{{ $s->name }}</option>`;
                @endforeach

                // Subtasks
                const subCont = document.getElementById('subtaskList');
                subCont.innerHTML = (task.subtasks || []).map(s => `
                    <div style="display: flex; align-items: center; gap: 12px; background: rgba(255,255,255,0.02); padding: 10px 16px; border-radius: 12px; border: 1px solid var(--border-color);">
                        <input type="checkbox" ${s.task_status_id == 3 ? 'checked' : ''} onchange="toggleSubtask(${s.id})" style="accent-color: var(--accent-color); width: 18px; height: 18px;">
                        <span style="font-size: 13px; color: var(--text-primary); flex-grow: 1; ${s.task_status_id == 3 ? 'text-decoration: line-through; opacity: 0.5;' : ''}">${s.title}</span>
                    </div>
                `).join('');
                if (subCont.innerHTML === '') subCont.innerHTML = '<p class="final-secondary-text" style="font-size: 11px;">No structural subtasks assigned.</p>';

                // Comments
                const commentCont = document.getElementById('commentList');
                commentCont.innerHTML = (task.comments || []).map(c => `
                    <div style="background: rgba(255,255,255,0.02); padding: 12px; border-radius: 12px; border: 1px solid var(--border-color);">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 6px;">
                            <span style="font-size: 11px; font-weight: 800; color: var(--accent-color);">${c.user ? c.user.name : 'Unknown'}</span>
                            <span style="font-size: 9px; color: var(--text-secondary);">${new Date(c.created_at).toLocaleDateString()}</span>
                        </div>
                        <div style="font-size: 12px; color: var(--text-primary);">${c.comment}</div>
                    </div>
                `).join('');
                if (commentCont.innerHTML === '') commentCont.innerHTML = '<p class="final-secondary-text" style="font-size: 11px;">No collaborative discussions yet.</p>';

                // Assignees & Watchers
                const assignedIds = (task.assignees || []).map(a => a.id);
                const watcherIds = (task.watchers || []).map(a => a.id);
                
                document.getElementById('assignedList').innerHTML = (task.assignees || []).map(a => `<span class="final-badge badge-email">${a.name}</span>`).join('');
                document.getElementById('watcherList').innerHTML = (task.watchers || []).map(a => `<span class="final-badge badge-inapp">${a.name}</span>`).join('');
                
                // Select options
                const aSel = document.getElementById('assigneeSelect');
                Array.from(aSel.options).forEach(opt => opt.selected = assignedIds.includes(parseInt(opt.value)));
                
                const wSel = document.getElementById('watcherSelect');
                Array.from(wSel.options).forEach(opt => opt.selected = watcherIds.includes(parseInt(opt.value)));

                // Timer Control
                const tControl = document.getElementById('timerControl');
                const noTControl = document.getElementById('noTimerControl');
                if (task.active_timer) {
                    tControl.style.display = 'block';
                    noTControl.style.display = 'none';
                    window.currentTimerId = task.active_timer.id;
                    const btn = document.getElementById('timerActionBtn');
                    if (task.active_timer.status === 'running') {
                        btn.innerHTML = '<i class="bi bi-pause-fill"></i> Pause Tracking';
                        btn.onclick = () => pauseTimer(task.active_timer.id);
                    } else {
                        btn.innerHTML = '<i class="bi bi-play-fill"></i> Resume Tracking';
                        btn.onclick = () => resumeTimer(task.active_timer.id);
                    }
                    // Update display
                    document.getElementById('timerDisplay').innerText = task.active_timer.total_seconds ? 
                        new Date(task.active_timer.total_seconds * 1000).toISOString().substr(11, 8) : '00:00:00';
                } else {
                    tControl.style.display = 'none';
                    noTControl.style.display = 'block';
                }

                // Status Button in Header
                const statusBtn = document.getElementById('modalStatusBtn');
                statusBtn.innerText = task.status ? task.status.name.toUpperCase() : 'PENDING';
                statusBtn.className = `final-btn final-btn-secondary ${task.status && task.status.id == 3 ? 'text-[var(--accent-color)]' : ''}`;
            })
            .catch(err => {
                console.error("Task loading error:", err);
                closeModal();
            });
    }

    function startTimer() {
        const id = document.getElementById('taskId').value;
        fetch(`/time-tracking/start`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
            body: JSON.stringify({ task_id: id })
        }).then(() => editTask(id));
    }

    function pauseTimer(id) {
        fetch(`/time-tracking/${id}/pause`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' }
        }).then(() => editTask(document.getElementById('taskId').value));
    }

    function resumeTimer(id) {
        fetch(`/time-tracking/${id}/resume`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' }
        }).then(() => editTask(document.getElementById('taskId').value));
    }

    function stopTimer() {
        const id = window.currentTimerId;
        if (!id) return;
        fetch(`/time-tracking/${id}/stop`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' }
        }).then(() => editTask(document.getElementById('taskId').value));
    }

    function addSubtask() {
        const id = document.getElementById('taskId').value;
        const title = prompt("Enter subtask objective:");
        if (!title) return;

        fetch(`/tasks/${id}/subtasks`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
            body: JSON.stringify({ title: title })
        }).then(() => editTask(id));
    }

    function postComment() {
        const id = document.getElementById('taskId').value;
        const comment = document.getElementById('newComment').value;
        if (!comment) return;

        fetch(`/tasks/${id}/comments/api`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
            body: JSON.stringify({ comment: comment })
        }).then(() => {
            document.getElementById('newComment').value = '';
            editTask(id);
        });
    }

    function toggleSubtask(id) {
        fetch(`/tasks/${id}/status`, {
            method: 'PATCH', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
            body: JSON.stringify({ task_status_id: 3 })
        }).then(() => editTask(document.getElementById('taskId').value));
    }

    function saveTask(e) {
        e.preventDefault();
        const id = document.getElementById('taskId').value;
        const form = document.getElementById('taskForm');
        const saveBtn = document.getElementById('saveBtn');
        
        saveBtn.disabled = true;
        saveBtn.innerHTML = '<i class="bi bi-arrow-repeat animate-spin"></i> Synchronizing...';

        const formData = new FormData(form);
        const data = {};
        formData.forEach((value, key) => {
            if (key.endsWith('[]')) {
                const cleanKey = key.slice(0, -2);
                if (!data[cleanKey]) data[cleanKey] = [];
                data[cleanKey].push(value);
            } else {
                data[key] = value;
            }
        });

        // Special handling for multiple selects
        data.assignee_ids = Array.from(document.getElementById('assigneeSelect').selectedOptions).map(o => o.value);
        data.watcher_ids = Array.from(document.getElementById('watcherSelect').selectedOptions).map(o => o.value);

        fetch(`/tasks/${id}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
            body: JSON.stringify(data)
        }).then(res => res.json())
          .then(() => window.location.reload())
          .catch(() => {
              saveBtn.disabled = false;
              saveBtn.innerHTML = '<i class="bi bi-save"></i> Synchronize Changes';
          });
    }

    function openCreateModal() {
        window.location.href = "{{ route('tasks.create') }}"; // Redirect to full create page as it's complex
    }
</script>
@endpush
@endsection


