@extends('layouts.app')
@section('title', $task->title)
@section('breadcrumb')
    <a href="{{ route('projects.index') }}" style="color:var(--text-secondary);">Projects</a>
    <span class="topbar-breadcrumb-sep">/</span>
    <a href="{{ route('projects.show', $task->project) }}" style="color:var(--text-secondary);">{{ $task->project->name }}</a>
    @if($task->parent)
        <span class="topbar-breadcrumb-sep">/</span>
        <a href="{{ route('tasks.show', $task->parent) }}" style="color:var(--text-secondary);">{{ Str::limit($task->parent->title, 25) }}</a>
        <span class="topbar-breadcrumb-sep">/</span>
        <span class="badge badge-primary" style="font-size:0.65rem;padding:2px 8px;vertical-align:middle;">Subtask</span>
    @else
        <span class="topbar-breadcrumb-sep">/</span>
    @endif
    <span style="font-weight:600;color:var(--text-primary);">{{ Str::limit($task->title, 30) }}</span>
@endsection

@section('content')
    <div class="td-layout">
        {{-- ===== MAIN TASK CONTENT ===== --}}
        <div class="td-main">
            {{-- Task Header Card --}}
            <div class="td-header-card">
                {{-- Status accent stripe --}}
                <div class="td-header-stripe" style="background: {{ $task->status_color }};"></div>

                <div class="td-header-inner">
                    {{-- Completion toggle --}}
                    <button type="button" class="td-complete-btn {{ $task->is_completed ? 'completed' : '' }}" onclick="document.getElementById('status-form-hidden').submit()">
                        <svg viewBox="0 0 24 24">
                            <circle cx="12" cy="12" r="10" class="td-complete-circle" />
                            <polyline points="8 12 11 15 16 9" class="td-complete-check" />
                        </svg>
                    </button>
                    <form id="status-form-hidden" method="POST" action="{{ route('tasks.update', $task) }}" style="display:none;">
                        @csrf @method('PUT')
                        <input type="hidden" name="status" value="{{ $task->is_completed ? 'todo' : 'completed' }}">
                    </form>

                    <div class="td-header-content">
                        <div class="td-title-row">
                            <h1 class="td-title {{ $task->is_completed ? 'completed' : '' }}">{{ $task->title }}</h1>
                            <div class="td-title-badges">
                                <span class="td-status-badge" style="background:{{ $task->status_color }}22;color:{{ $task->status_color }};border-color:{{ $task->status_color }}44;">
                                    {{ ucfirst(str_replace('_', ' ', $task->status)) }}
                                </span>
                                <span class="td-priority-badge td-priority-{{ $task->priority }}">
                                    <span class="td-priority-dot" style="background:{{ $task->priority_color }};"></span>
                                    {{ ucfirst($task->priority) }}
                                </span>
                            </div>
                        </div>
                        @if($task->subtask_progress && $task->subtask_progress['total'] > 0)
                            <div class="td-header-progress">
                                <div class="td-header-progress-track">
                                    <div class="td-header-progress-bar {{ $task->subtask_progress['percent'] >= 100 ? 'complete' : '' }}" style="width:{{ $task->subtask_progress['percent'] }}%"></div>
                                </div>
                                <span class="td-header-progress-text">{{ $task->subtask_progress['completed'] }}/{{ $task->subtask_progress['total'] }} subtasks</span>
                            </div>
                        @endif
                    </div>
                </div>
            </div>

            {{-- Description --}}
            <div class="td-section">
                <div class="td-section-header">
                    <div class="td-section-icon" style="background:rgba(99,102,241,0.12);color:var(--accent-primary);">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
                    </div>
                    <h3 class="td-section-title">Description</h3>
                </div>
                @if($task->description)
                    <p class="td-description">{{ $task->description }}</p>
                @else
                    <p class="td-description td-empty-text">No description added. Click to add one...</p>
                @endif
            </div>

            {{-- ===== SUBTASKS ===== --}}
            <div class="td-section" x-data="subtaskManager({{ $task->id }}, {{ json_encode($task->subtask_progress) }})">
                <div class="td-section-header">
                    <div class="td-section-icon" style="background:rgba(34,197,94,0.12);color:var(--accent-green);">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
                    </div>
                    <h3 class="td-section-title">Subtasks</h3>
                    <div class="td-section-meta" x-show="progress.total > 0">
                        <div class="td-micro-progress">
                            <div class="td-micro-progress-bar" :class="{ 'complete': progress.percent === 100 }" :style="'width:' + progress.percent + '%'"></div>
                        </div>
                        <span class="td-section-count" x-text="progress.completed + '/' + progress.total"></span>
                    </div>
                    <div style="margin-left:auto;">
                        <button type="button" class="td-add-btn" @click="showAddForm = !showAddForm" :class="{ 'active': showAddForm }">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                            Add
                        </button>
                    </div>
                </div>

                {{-- Subtask List --}}
                <div class="subtask-list" x-ref="subtaskList">
                    @foreach($task->subtasksRecursive as $sub)
                        @include('tasks.partials.subtask-item', ['sub' => $sub, 'users' => $users, 'level' => 0])
                    @endforeach
                </div>

                {{-- Add Subtask Form --}}
                <div class="subtask-add-form" x-show="showAddForm" x-transition.opacity.duration.200ms x-cloak>
                    <div class="subtask-add-form-inner">
                        <div class="subtask-check disabled">
                            <svg viewBox="0 0 24 24" class="subtask-check-svg"><circle cx="12" cy="12" r="10" class="subtask-check-circle"/></svg>
                        </div>
                        <input type="text" class="subtask-add-input" placeholder="What needs to be done?"
                               x-ref="newSubtaskInput"
                               @keydown.enter="addSubtask($refs.newSubtaskInput.value); $refs.newSubtaskInput.value = ''"
                               @keydown.escape="showAddForm = false">
                        <div class="subtask-add-form-actions">
                            <select x-ref="newSubtaskAssignee" class="subtask-add-select">
                                <option value="">Assignee</option>
                                @foreach($users as $u)
                                    <option value="{{ $u->id }}">{{ $u->name }}</option>
                                @endforeach
                            </select>
                            <input type="date" x-ref="newSubtaskDue" class="subtask-add-date">
                            <button type="button" class="btn btn-primary btn-sm" @click="addSubtask($refs.newSubtaskInput.value); $refs.newSubtaskInput.value = ''">Add</button>
                        </div>
                    </div>
                </div>

                {{-- Empty state --}}
                <div class="td-empty-state" x-show="progress.total === 0 && !showAddForm">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
                    <p>No subtasks yet. Break this task down!</p>
                </div>
            </div>

            {{-- ===== COMMENTS (Chat-bubble style) ===== --}}
            <div class="td-section">
                <div class="td-section-header">
                    <div class="td-section-icon" style="background:rgba(59,130,246,0.12);color:var(--accent-blue);">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
                    </div>
                    <h3 class="td-section-title">Comments</h3>
                    <span class="td-section-count">{{ $task->comments->count() }}</span>
                </div>

                <div class="td-comments-list">
                    @foreach($task->comments as $comment)
                        <div class="td-comment {{ $comment->user_id === auth()->id() ? 'td-comment-own' : '' }}">
                            <div class="td-comment-avatar">
                                <div class="avatar avatar-sm" style="background:{{ ['#6366f1','#ec4899','#f59e0b','#22c55e','#3b82f6','#8b5cf6'][($comment->user_id ?? 0) % 6] }};">{{ $comment->user->initials }}</div>
                            </div>
                            <div class="td-comment-bubble">
                                <div class="td-comment-header">
                                    <span class="td-comment-author">{{ $comment->user->name }}</span>
                                    <span class="td-comment-time">{{ $comment->created_at->diffForHumans() }}</span>
                                    <form method="POST" action="{{ route('comments.destroy', $comment) }}" style="margin:0;margin-left:auto;" onsubmit="return confirm('Delete comment?')">
                                        @csrf @method('DELETE')
                                        <button type="submit" class="td-comment-delete" title="Delete">
                                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                                        </button>
                                    </form>
                                </div>
                                <div class="td-comment-text">{{ $comment->body }}</div>
                            </div>
                        </div>
                    @endforeach
                </div>

                {{-- New Comment --}}
                <form method="POST" action="{{ route('comments.store', $task) }}" class="td-comment-form">
                    @csrf
                    <div class="avatar avatar-sm" style="flex-shrink:0;">{{ auth()->user()->initials }}</div>
                    <div class="td-comment-input-wrap">
                        <textarea name="body" class="td-comment-input" rows="1" placeholder="Write a comment..." required oninput="this.style.height='auto';this.style.height=this.scrollHeight+'px';"></textarea>
                        <button type="submit" class="td-comment-send" title="Send">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
                        </button>
                    </div>
                </form>
            </div>

            {{-- ===== ATTACHMENTS ===== --}}
            <div class="td-section">
                <div class="td-section-header">
                    <div class="td-section-icon" style="background:rgba(236,72,153,0.12);color:var(--accent-pink);">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
                    </div>
                    <h3 class="td-section-title">Attachments</h3>
                    <span class="td-section-count">{{ $task->attachments->count() }}</span>
                </div>

                @if($task->attachments->count())
                <div class="td-attachments-grid">
                    @foreach($task->attachments as $att)
                        @php
                            $ext = pathinfo($att->original_filename, PATHINFO_EXTENSION);
                            $isImage = in_array(strtolower($ext), ['jpg','jpeg','png','gif','webp','svg']);
                            $iconColors = ['pdf' => '#ef4444', 'doc' => '#3b82f6', 'docx' => '#3b82f6', 'xls' => '#22c55e', 'xlsx' => '#22c55e', 'zip' => '#f59e0b', 'rar' => '#f59e0b', 'txt' => '#6b7280', 'csv' => '#22c55e'];
                            $fileColor = $iconColors[strtolower($ext)] ?? '#8b5cf6';
                        @endphp
                        <div class="td-attachment-card">
                            <div class="td-attachment-preview" style="background:{{ $fileColor }}11;">
                                @if($isImage)
                                    <img src="{{ $att->url }}" alt="{{ $att->original_filename }}" loading="lazy">
                                @else
                                    <div class="td-attachment-ext" style="color:{{ $fileColor }};">.{{ strtoupper($ext) }}</div>
                                @endif
                            </div>
                            <div class="td-attachment-info">
                                <a href="{{ $att->url }}" target="_blank" class="td-attachment-name" title="{{ $att->original_filename }}">{{ Str::limit($att->original_filename, 20) }}</a>
                                <span class="td-attachment-meta">{{ $att->human_size }} · {{ $att->created_at->diffForHumans() }}</span>
                            </div>
                            <div class="td-attachment-actions">
                                <a href="{{ $att->url }}" download class="td-attach-action" title="Download">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                                </a>
                                <form method="POST" action="{{ route('attachments.destroy', $att) }}" style="margin:0" onsubmit="return confirm('Delete?')">
                                    @csrf @method('DELETE')
                                    <button type="submit" class="td-attach-action danger" title="Delete">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                                    </button>
                                </form>
                            </div>
                        </div>
                    @endforeach
                </div>
                @endif

                <form method="POST" action="{{ route('attachments.store', $task) }}" enctype="multipart/form-data" class="td-upload-form">
                    @csrf
                    <label class="td-upload-area">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                        <span>Drop files here or <strong>browse</strong></span>
                        <input type="file" name="file" style="display:none;" onchange="this.form.submit()">
                    </label>
                </form>
            </div>

            {{-- ===== DEPENDENCIES ===== --}}
            <div class="td-section" x-data="dependencyManager()">
                <div class="td-section-header">
                    <div class="td-section-icon" style="background:rgba(249,115,22,0.12);color:#f97316;">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
                    </div>
                    <h3 class="td-section-title">Dependencies</h3>
                    @if($task->is_blocked)
                        <span class="td-blocked-badge">🚫 Blocked</span>
                    @endif
                </div>

                @if($task->dependencies->count())
                    <div class="dependency-list">
                        @foreach($task->dependencies as $dep)
                            <div class="dependency-item" id="dep-{{ $dep->id }}">
                                <div class="flex items-center gap-2" style="flex:1;min-width:0;">
                                    <div class="task-checkbox {{ $dep->is_completed ? 'completed' : '' }}" style="width:16px;height:16px;"></div>
                                    <a href="{{ route('tasks.show', $dep) }}" style="color:var(--text-primary);font-size:0.85rem;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="{{ $dep->title }}">
                                        {{ Str::limit($dep->title, 35) }}
                                    </a>
                                </div>
                                <div class="flex items-center gap-2">
                                    <span class="badge badge-{{ $dep->is_completed ? 'success' : 'secondary' }}" style="font-size:0.65rem;">{{ ucfirst(str_replace('_', ' ', $dep->status)) }}</span>
                                    <button type="button" class="btn btn-ghost btn-icon btn-sm" style="color:var(--accent-red);" title="Remove" @click="removeDependency({{ $dep->id }}, $el)">✕</button>
                                </div>
                            </div>
                        @endforeach
                    </div>
                @endif

                <div class="mt-2" style="position:relative;">
                    <button type="button" class="td-add-btn" @click="open = !open" style="font-size:0.8rem;">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                        Add Dependency
                    </button>
                    <div class="tag-selector-dropdown" x-show="open" @click.away="open = false" x-cloak x-transition style="max-height:200px;overflow-y:auto;width:280px;">
                        @if(isset($projectTasks))
                            @foreach($projectTasks as $pt)
                                @if(!$task->dependencies->contains($pt->id))
                                    <button type="button" class="tag-selector-item" @click="addDependency({{ $pt->id }}, $el)">
                                        <div class="task-checkbox {{ $pt->status === 'completed' ? 'completed' : '' }}" style="width:14px;height:14px;"></div>
                                        <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">{{ Str::limit($pt->title, 30) }}</span>
                                    </button>
                                @endif
                            @endforeach
                        @endif
                    </div>
                </div>

                @if($task->dependents->count())
                    <div class="mt-3">
                        <h4 class="text-xs text-muted mb-1" style="font-weight:600;">Blocks {{ $task->dependents->count() }} task(s):</h4>
                        @foreach($task->dependents as $dependent)
                            <div style="display:flex;align-items:center;gap:8px;padding:4px 0;">
                                <span style="color:var(--accent-red);font-size:0.75rem;">→</span>
                                <a href="{{ route('tasks.show', $dependent) }}" style="font-size:0.8rem;color:var(--text-secondary);">{{ Str::limit($dependent->title, 30) }}</a>
                            </div>
                        @endforeach
                    </div>
                @endif
            </div>

            {{-- ===== ACTIVITY ===== --}}
            <div class="td-section">
                <div class="td-section-header">
                    <div class="td-section-icon" style="background:rgba(139,92,246,0.12);color:#8b5cf6;">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline></svg>
                    </div>
                    <h3 class="td-section-title">Activity</h3>
                </div>
                @if(isset($taskActivities) && $taskActivities->count())
                <div class="activity-timeline activity-timeline-compact">
                    @foreach($taskActivities as $activity)
                        <div class="activity-timeline-item">
                            <div class="activity-timeline-connector">
                                <div class="activity-timeline-dot" style="background:{{ $activity->color }}1a;color:{{ $activity->color }};border-color:{{ $activity->color }}33;">
                                    {!! $activity->svg_icon !!}
                                </div>
                                @if(!$loop->last)
                                    <div class="activity-timeline-line"></div>
                                @endif
                            </div>
                            <div class="activity-timeline-content">
                                <div class="activity-timeline-text">
                                    <strong>{{ $activity->causer->name ?? 'System' }}</strong>
                                    <span>{{ $activity->description }}</span>
                                </div>
                                <div class="activity-timeline-meta">
                                    <span class="activity-timeline-time">{{ $activity->created_at->diffForHumans() }}</span>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
                @else
                <div class="td-empty-state">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline></svg>
                    <p>No activity recorded yet.</p>
                </div>
                @endif
            </div>
        </div>

        {{-- ===== RIGHT SIDEBAR — DETAILS PANEL ===== --}}
        <div class="td-sidebar">
            <div class="td-details-card">
                <div class="td-details-header">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
                    <span>Details</span>
                </div>

                <form method="POST" action="{{ route('tasks.update', $task) }}" class="td-details-form">
                    @csrf @method('PUT')

                    {{-- Status --}}
                    <div class="td-detail-field">
                        <div class="td-detail-label">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                            Status
                        </div>
                        <div class="td-detail-value">
                            <select name="status" class="td-detail-select" onchange="this.form.submit()">
                                @foreach(['todo' => 'To Do', 'in_progress' => 'In Progress', 'review' => 'Review', 'completed' => 'Completed'] as $val => $label)
                                    <option value="{{ $val }}" {{ $task->status == $val ? 'selected' : '' }}>{{ $label }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    {{-- Assignee --}}
                    <div class="td-detail-field">
                        <div class="td-detail-label">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                            Assignee
                        </div>
                        <div class="td-detail-value">
                            @if($task->assignee)
                                <div class="avatar avatar-xs" style="flex-shrink:0;">{{ $task->assignee->initials }}</div>
                            @endif
                            <select name="assignee_id" class="td-detail-select" onchange="this.form.submit()">
                                <option value="">Unassigned</option>
                                @foreach($users as $u)
                                    <option value="{{ $u->id }}" {{ $task->assignee_id == $u->id ? 'selected' : '' }}>{{ $u->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    {{-- Priority --}}
                    <div class="td-detail-field">
                        <div class="td-detail-label">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/></svg>
                            Priority
                        </div>
                        <div class="td-detail-value">
                            <span class="td-priority-dot" style="background:{{ $task->priority_color }};flex-shrink:0;"></span>
                            <select name="priority" class="td-detail-select" onchange="this.form.submit()">
                                @foreach(['low','medium','high','urgent'] as $p)
                                    <option value="{{ $p }}" {{ $task->priority == $p ? 'selected' : '' }}>{{ ucfirst($p) }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    {{-- Due Date --}}
                    <div class="td-detail-field">
                        <div class="td-detail-label">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                            Due Date
                        </div>
                        <div class="td-detail-value">
                            <input type="date" name="due_date" class="td-detail-date" value="{{ $task->due_date?->format('Y-m-d') }}" onchange="this.form.submit()">
                        </div>
                    </div>
                </form>

                {{-- Meta --}}
                <div class="td-details-meta">
                    <div class="td-meta-row">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg>
                        <span>Project</span>
                        <a href="{{ route('projects.show', $task->project) }}" class="td-meta-value">{{ $task->project->name }}</a>
                    </div>
                    <div class="td-meta-row">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                        <span>Created by</span>
                        <span class="td-meta-value">{{ $task->creator->name }}</span>
                    </div>
                    <div class="td-meta-row">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                        <span>Created</span>
                        <span class="td-meta-value">{{ $task->created_at->format('M j, Y') }}</span>
                    </div>
                    @if($task->completed_at)
                    <div class="td-meta-row">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                        <span>Completed</span>
                        <span class="td-meta-value">{{ $task->completed_at->format('M j, Y') }}</span>
                    </div>
                    @endif
                </div>

                {{-- Tags --}}
                <div class="td-details-tags" x-data="tagManager()">
                    <div class="td-detail-label" style="margin-bottom:8px;">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.83z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>
                        Tags
                    </div>
                    <div class="flex gap-1 flex-wrap" id="task-tags">
                        @foreach($task->tags as $tag)
                            <span class="badge tag-removable" style="background:{{ $tag->color }}22;color:{{ $tag->color }};" title="Click to remove" @click="removeTag({{ $tag->id }}, $el)">
                                {{ $tag->name }} ×
                            </span>
                        @endforeach
                    </div>
                    <div class="tag-selector-wrap mt-2">
                        <button type="button" class="td-add-btn" @click="open = !open" style="font-size:0.78rem;">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                            Add Tag
                        </button>
                        <div class="tag-selector-dropdown" x-show="open" @click.away="open = false" x-cloak x-transition>
                            @foreach($allTags as $at)
                                <button type="button" class="tag-selector-item" data-tag-id="{{ $at->id }}" data-tag-name="{{ $at->name }}" data-tag-color="{{ $at->color }}" @click="addTag({{ $at->id }}, '{{ $at->name }}', '{{ $at->color }}', $el)">
                                    <span class="tag-selector-dot" style="background:{{ $at->color }};"></span>
                                    {{ $at->name }}
                                </button>
                            @endforeach
                            @if($allTags->isEmpty())
                                <div class="text-xs text-muted" style="padding:8px 10px;">No tags available</div>
                            @endif
                        </div>
                    </div>
                </div>
            </div>

            {{-- Delete (subtle) --}}
            <form method="POST" action="{{ route('tasks.destroy', $task) }}" onsubmit="return confirm('Are you sure you want to delete this task?')" class="td-delete-form">
                @csrf @method('DELETE')
                <button type="submit" class="td-delete-btn">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                    Delete Task
                </button>
            </form>
        </div>
    </div>
@endsection

@push('scripts')
<script>
const CSRF_TOKEN = document.querySelector('meta[name="csrf-token"]').content;
const API_HEADERS = {
    'Content-Type': 'application/json',
    'X-CSRF-TOKEN': CSRF_TOKEN,
    'Accept': 'application/json'
};
</script>
@endpush

@push('scripts')
<script>
function subtaskManager(taskId, initialProgress) {
    return {
        progress: initialProgress || { completed: 0, total: 0, percent: 0 },
        showAddForm: false,

        init() {
            this.initSortable(this.$refs.subtaskList);
            this.$el.querySelectorAll('.subtask-children').forEach(list => {
                this.initSortable(list);
            });
        },

        initSortable(el) {
            if (!el) return;
            new Sortable(el, {
                group: 'subtasks',
                handle: '.subtask-drag-handle',
                animation: 200,
                ghostClass: 'subtask-ghost',
                chosenClass: 'subtask-chosen',
                dragClass: 'subtask-drag',
                fallbackOnBody: true,
                swapThreshold: 0.65,
                onEnd: (evt) => {
                    const listEl = evt.item.parentElement;
                    const newParentId = listEl.dataset.parent || null;
                    const ids = [...listEl.querySelectorAll(':scope > .subtask-item')].map(el => el.dataset.id);
                    fetch(`/tasks/${taskId}/subtasks/reorder`, {
                        method: 'POST', headers: API_HEADERS,
                        body: JSON.stringify({ order: ids, parent_id: newParentId })
                    });
                }
            });
        },

        toggleComplete(subtaskId, el) {
            const item = el.closest('.subtask-item');
            const isCompleted = item.classList.toggle('is-completed');
            el.classList.toggle('checked');

            fetch(`/tasks/subtasks/${subtaskId}/toggle`, {
                method: 'POST', headers: API_HEADERS,
                body: JSON.stringify({ is_completed: isCompleted })
            })
            .then(r => r.json())
            .then(data => {
                if (data.progress) this.progress = data.progress;
            });
        },

        updateSubtask(subtaskId, field, value) {
            fetch(`/tasks/subtasks/${subtaskId}`, {
                method: 'PUT', headers: API_HEADERS,
                body: JSON.stringify({ [field]: value })
            });
        },

        deleteSubtask(subtaskId, el) {
            if (!confirm('Delete this subtask?')) return;
            const item = el.closest('.subtask-item');
            item.style.opacity = '0';
            item.style.transform = 'translateX(20px)';
            setTimeout(() => {
                item.remove();
                fetch(`/tasks/subtasks/${subtaskId}`, {
                    method: 'DELETE', headers: API_HEADERS
                }).then(r => r.json()).then(data => {
                    if (data.progress) this.progress = data.progress;
                });
            }, 250);
        },

        addSubtask(title) {
            if (!title.trim()) return;
            const assigneeId = this.$refs.newSubtaskAssignee?.value || null;
            const dueDate = this.$refs.newSubtaskDue?.value || null;
            fetch(`/tasks/${taskId}/subtasks`, {
                method: 'POST', headers: API_HEADERS,
                body: JSON.stringify({ title, assignee_id: assigneeId, due_date: dueDate })
            })
            .then(r => r.json())
            .then(data => {
                if (data.html) {
                    this.$refs.subtaskList.insertAdjacentHTML('beforeend', data.html);
                    this.initSortable(this.$refs.subtaskList);
                }
                if (data.progress) this.progress = data.progress;
            });
        },

        showNestedForm(parentId) {
            const form = document.getElementById('nested-form-' + parentId);
            if (form) {
                form.style.display = form.style.display === 'none' ? 'block' : 'none';
                const input = form.querySelector('input[type="text"]');
                if (input) input.focus();
            }
        }
    };
}

function submitNestedSubtask(btn) {
    const form = btn.closest('.subtask-nested-form');
    const input = form.querySelector('.subtask-nested-input');
    const title = input.value.trim();
    if (!title) return;
    const parentId = input.dataset.parent;
    const projectId = input.dataset.project;

    fetch(`/tasks/${parentId}/subtasks`, {
        method: 'POST', headers: API_HEADERS,
        body: JSON.stringify({ title, project_id: projectId })
    })
    .then(r => r.json())
    .then(() => location.reload());
}

function tagManager() {
    return {
        open: false,
        addTag(tagId, tagName, tagColor, el) {
            fetch(`/tasks/{{ $task->id }}/tags`, {
                method: 'POST', headers: API_HEADERS,
                body: JSON.stringify({ tag_id: tagId })
            }).then(r => r.json()).then(() => {
                const container = document.getElementById('task-tags');
                const badge = document.createElement('span');
                badge.className = 'badge tag-removable';
                badge.style.cssText = `background:${tagColor}22;color:${tagColor};`;
                badge.innerHTML = `${tagName} ×`;
                badge.onclick = () => this.removeTag(tagId, badge);
                container.appendChild(badge);
                if (el) el.remove();
            });
        },
        removeTag(tagId, el) {
            fetch(`/tasks/{{ $task->id }}/tags/${tagId}`, {
                method: 'DELETE', headers: API_HEADERS
            }).then(() => el.remove());
        }
    };
}

function dependencyManager() {
    return {
        open: false,
        addDependency(depId, el) {
            fetch(`/tasks/{{ $task->id }}/dependencies`, {
                method: 'POST', headers: API_HEADERS,
                body: JSON.stringify({ dependency_id: depId })
            }).then(r => r.json()).then(() => location.reload());
        },
        removeDependency(depId) {
            fetch(`/tasks/{{ $task->id }}/dependencies/${depId}`, {
                method: 'DELETE', headers: API_HEADERS
            }).then(r => r.json()).then(() => {
                document.getElementById('dep-' + depId)?.remove();
            });
        }
    };
}
</script>
@endpush
