<?php $pageTitle = Helper::e($task['title']); ?>

<div class="page-header">
    <div class="page-header-left">
        <a href="/project/<?= $task['project_id'] ?>" class="btn btn-ghost btn-sm">
            <span class="project-dot" style="background:<?= Helper::e($task['project_color']) ?>"></span>
            <?= Helper::e($task['project_name']) ?>
        </a>
        <h1 class="page-title task-detail-title"><?= Helper::e($task['title']) ?></h1>
    </div>
    <div class="page-header-actions">
        <?php if (in_array($myRole, ['owner','manager','member'])): ?>
        <a href="/task/<?= $task['id'] ?>/edit" class="btn btn-ghost btn-sm"><?= t('edit') ?></a>
        <?php endif; ?>
    </div>
</div>

<?php if ($success): ?><div class="alert alert-success"><?= Helper::e($success) ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-error"><?= Helper::e($error) ?></div><?php endif; ?>

<div class="task-detail-layout">
    <!-- Main content -->
    <div class="task-detail-main">
        <!-- Description -->
        <?php if ($task['description']): ?>
        <div class="card">
            <div class="card-header"><h2 class="card-title"><?= t('task_desc') ?></h2></div>
            <div class="card-body">
                <div class="task-description rich-content"><?= renderHtmlContent($task['description']) ?></div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Attachments -->
        <?php if (!empty($attachments)): ?>
        <div class="card">
            <div class="card-header"><h2 class="card-title"><?= t('attachments') ?></h2></div>
            <div class="card-body">
                <div class="attachment-grid">
                    <?php foreach ($attachments as $att): ?>
                    <div class="attachment-item">
                        <div class="attachment-icon">
                            <?php
                            $ext = strtolower(pathinfo($att['original_name'], PATHINFO_EXTENSION));
                            $iconClass = match(true) {
                                in_array($ext, ['jpg','jpeg','png','gif','webp']) => 'icon-img',
                                in_array($ext, ['pdf']) => 'icon-pdf',
                                in_array($ext, ['doc','docx']) => 'icon-doc',
                                in_array($ext, ['xls','xlsx','csv']) => 'icon-sheet',
                                default => 'icon-file'
                            };
                            ?>
                            <span class="file-type-icon <?= $iconClass ?>"><?= strtoupper($ext) ?></span>
                        </div>
                        <div class="attachment-info">
                            <a href="/attachment/<?= $att['id'] ?>/download" class="attachment-name"><?= Helper::e($att['original_name']) ?></a>
                            <span class="attachment-meta">
                                <?= Helper::e($att['username']) ?> · <?= Helper::formatDateTime($att['created_at']) ?>
                                <?php if ($att['file_size']): ?>· <?= number_format($att['file_size'] / 1024, 0) ?> KB<?php endif; ?>
                            </span>
                        </div>
                        <?php if ($att['user_id'] == Auth::id() || in_array($myRole, ['owner','manager'])): ?>
                        <form method="POST" action="/attachment/<?= $att['id'] ?>/delete" data-confirm="<?= Helper::e(t('confirm_delete')) ?>">
                            <?= Helper::csrf() ?>
                            <button type="submit" class="icon-btn-sm danger">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
                            </button>
                        </form>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Comments -->
        <div class="card">
            <div class="card-header"><h2 class="card-title"><?= t('comments') ?> (<?= count($comments) ?>)</h2></div>
            <div class="card-body">
                <?php if (empty($comments)): ?>
                <p class="text-muted"><?= t('no_comments') ?></p>
                <?php endif; ?>
                <div class="comments-list">
                    <?php foreach ($comments as $comment): ?>
                    <div class="comment" id="comment-<?= $comment['id'] ?>">
                        <div class="comment-avatar">
                            <?php if ($comment['user_id']): ?>
                            <?= Helper::avatar(['username' => $comment['username'] ?? '?', 'avatar' => $comment['avatar'], 'id' => $comment['user_id']], 32) ?>
                            <?php else: ?>
                            <span class="avatar-initials avatar-ext" style="width:32px;height:32px;font-size:13px"><?= Helper::e(mb_strtoupper(mb_substr((string)($comment['external_name'] ?? '?'),0,1))) ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="comment-body">
                            <div class="comment-header">
                                <strong>
                                    <?= Helper::e($comment['user_id'] ? ($comment['username'] ?? '—') : ($comment['external_name'] ?? 'Extern')) ?>
                                    <?php if (!$comment['user_id']): ?><span class="badge-ext" style="font-size:10px"><?= t('external_short') ?></span><?php endif; ?>
                                </strong>
                                <span class="comment-time"><?= Helper::timeAgo($comment['created_at']) ?></span>
                                <?php if ($comment['is_edited']): ?><span class="comment-edited">(<?= t('edited') ?>)</span><?php endif; ?>
                                <?php if (($comment['user_id'] && $comment['user_id'] == Auth::id()) || in_array($myRole, ['owner','manager'])): ?>
                                <button class="icon-btn-sm danger comment-delete-btn"
                                        data-id="<?= $comment['id'] ?>" title="<?= t('delete') ?>">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="12" height="12"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
                                </button>
                                <?php endif; ?>
                            </div>
                            <div class="comment-content rich-content"><?= renderHtmlContent($comment['content']) ?></div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <?php if (in_array($myRole, ['owner','manager','member'])): ?>
                <?php
                $mentionData = [];
                foreach ($members as $m) $mentionData[] = ['key' => $m['username'], 'display' => $m['username'], 'type' => 'user'];
                foreach ($projectExternals as $e) $mentionData[] = ['key' => $e['name'], 'display' => $e['name'], 'type' => 'ext'];
                ?>
                <form method="POST" action="/task/<?= $task['id'] ?>/comment" class="comment-form">
                    <?= Helper::csrf() ?>
                    <div class="comment-input-row">
                        <?= Helper::avatar(Auth::user(), 32) ?>
                        <div class="comment-input-wrap">
                            <div id="comment-editor" class="rich-editor-wrap" style="min-height:80px"></div>
                            <input type="hidden" name="content" id="comment-hidden">
                            <button type="submit" class="btn btn-primary btn-sm" style="margin-top:8px"><?= t('add_comment') ?></button>
                        </div>
                    </div>
                </form>
                <?php endif; ?>
            </div>
        </div>

    </div>

    <!-- Sidebar -->
    <div class="task-detail-sidebar">
        <div class="card">
            <div class="card-body">
                <!-- Status -->
                <div class="task-meta-item">
                    <span class="task-meta-label"><?= t('task_status') ?></span>
                    <?php if (in_array($myRole, ['owner','manager','member'])): ?>
                    <form method="POST" action="/task/<?= $task['id'] ?>/edit" class="meta-inline-form">
                        <?= Helper::csrf() ?>
                        <input type="hidden" name="action" value="change_status">
                        <select name="status_id" class="meta-select status-meta-select"
                                style="--status-color:<?= Helper::e($task['status_color'] ?? '#6b7280') ?>" data-auto-submit>
                            <?php foreach ($statuses as $s): ?>
                            <option value="<?= $s['id'] ?>"
                                    data-color="<?= Helper::e($s['color']) ?>"
                                    <?= $task['status_id'] == $s['id'] ? 'selected' : '' ?>>
                                <?= Helper::e($s['name']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </form>
                    <?php else: ?>
                    <span class="status-badge" style="--status-color:<?= Helper::e($task['status_color'] ?? '#6b7280') ?>">
                        <?= Helper::e($task['status_name'] ?? '—') ?>
                    </span>
                    <?php endif; ?>
                </div>
                <!-- Priority -->
                <div class="task-meta-item">
                    <span class="task-meta-label"><?= t('priority') ?></span>
                    <?php if (in_array($myRole, ['owner','manager','member'])): ?>
                    <form method="POST" action="/task/<?= $task['id'] ?>/edit" class="meta-inline-form">
                        <?= Helper::csrf() ?>
                        <input type="hidden" name="action" value="change_priority">
                        <select name="priority" class="meta-select priority-meta-select priority-<?= Helper::e($task['priority'] ?? 'medium') ?>"
                                data-change="prioritySubmit">
                            <option value="low"    <?= ($task['priority']??'') === 'low'    ? 'selected' : '' ?>><?= t('priority_low') ?></option>
                            <option value="medium" <?= ($task['priority']??'') === 'medium' ? 'selected' : '' ?>><?= t('priority_medium') ?></option>
                            <option value="high"   <?= ($task['priority']??'') === 'high'   ? 'selected' : '' ?>><?= t('priority_high') ?></option>
                            <option value="urgent" <?= ($task['priority']??'') === 'urgent' ? 'selected' : '' ?>><?= t('priority_urgent') ?></option>
                        </select>
                    </form>
                    <?php else: ?>
                    <?= Helper::priorityBadge($task['priority']) ?>
                    <?php endif; ?>
                </div>
                <div class="task-meta-item task-meta-assignees">
                    <span class="task-meta-label"><?= t('assigned_to') ?></span>
                    <?= Helper::assigneeChips($assignees ?? [], 20) ?>
                </div>
                <div class="task-meta-item">
                    <span class="task-meta-label"><?= t('created_by') ?></span>
                    <span><?= Helper::e($task['creator_name'] ?? '—') ?></span>
                </div>
                <!-- Dates -->
                <?php if (in_array($myRole, ['owner','manager','member'])): ?>
                <form method="POST" action="/task/<?= $task['id'] ?>/edit" class="date-inline-form">
                    <?= Helper::csrf() ?>
                    <input type="hidden" name="action" value="update_dates">
                    <div class="task-meta-item">
                        <span class="task-meta-label"><?= t('start_date') ?></span>
                        <input type="date" name="start_date" class="date-inline-input"
                               value="<?= Helper::e($task['start_date'] ?? '') ?>" data-auto-submit>
                    </div>
                    <div class="task-meta-item">
                        <span class="task-meta-label"><?= t('due_date') ?></span>
                        <input type="date" name="due_date" class="date-inline-input <?= ($task['due_date'] && $task['due_date'] < date('Y-m-d')) ? 'overdue' : '' ?>"
                               value="<?= Helper::e($task['due_date'] ?? '') ?>" data-auto-submit>
                    </div>
                </form>
                <?php else: ?>
                <?php if ($task['start_date']): ?>
                <div class="task-meta-item">
                    <span class="task-meta-label"><?= t('start_date') ?></span>
                    <span><?= Helper::formatDate($task['start_date']) ?></span>
                </div>
                <?php endif; ?>
                <?php if ($task['due_date']): ?>
                <div class="task-meta-item">
                    <span class="task-meta-label"><?= t('due_date') ?></span>
                    <span class="task-due <?= $task['due_date'] < date('Y-m-d') ? 'overdue' : '' ?>">
                        <?= Helper::formatDate($task['due_date']) ?>
                    </span>
                </div>
                <?php endif; ?>
                <?php endif; ?>
                <!-- Labels -->
                <?php if (!empty($taskLabels)): ?>
                <div class="task-meta-item task-meta-labels">
                    <span class="task-meta-label"><?= t('labels') ?></span>
                    <div class="task-labels">
                        <?php foreach ($taskLabels as $label): ?>
                        <span class="label-badge" style="background:<?= Helper::e($label['color']) ?>20;color:<?= Helper::e($label['color']) ?>;border:1px solid <?= Helper::e($label['color']) ?>40">
                            <?= Helper::e($label['name']) ?>
                        </span>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <div class="task-meta-item">
                    <span class="task-meta-label"><?= t('created_at_label') ?></span>
                    <span><?= Helper::formatDateTime($task['created_at']) ?></span>
                </div>
                <div class="task-meta-item">
                    <span class="task-meta-label"><?= t('updated_at_label') ?></span>
                    <span><?= Helper::formatDateTime($task['updated_at']) ?></span>
                </div>
            </div>
        </div>

        <!-- Assignees inline edit -->
        <?php if (in_array($myRole, ['owner','manager','member'])): ?>
        <?php
        $_aUserIds    = array_column(array_filter($assignees ?? [], fn($a) => !empty($a['user_id'])), 'user_id');
        $_aExtIds     = array_column(array_filter($assignees ?? [], fn($a) => !empty($a['external_id'])), 'external_id');
        $_aDummies    = array_column(array_filter($assignees ?? [], fn($a) => empty($a['user_id']) && empty($a['external_id'])), 'external_name');
        $_allProjExts = $projectExternals ?? [];
        $_projExtWithEmail = array_values(array_filter($_allProjExts, fn($p) => !empty($p['email'])));
        $_projDummies      = array_values(array_filter($_allProjExts, fn($p) => empty($p['email'])));
        ?>
        <div class="card">
            <div class="card-header">
                <h2 class="card-title"><?= t('assigned_to') ?></h2>
                <button type="button" class="dep-toggle-btn" id="assigneeToggleBtn" data-click="toggleAssigneeForm">
                    <?= t('edit') ?>
                </button>
            </div>
            <!-- Read view -->
            <div id="assigneeReadView" class="card-body dep-card">
                <?= Helper::assigneeChips($assignees ?? [], 22) ?>
            </div>
            <!-- Edit form -->
            <div id="assigneeEditView" class="dep-edit-view" style="display:none">
                <form method="POST" action="/task/<?= $task['id'] ?>/edit">
                    <?= Helper::csrf() ?>
                    <input type="hidden" name="action" value="update_assignees">
                    <div class="dep-form-body">
                        <!-- System users -->
                        <?php if (!empty($members ?? [])): ?>
                        <?php $__members = $members ?? []; ?>
                        <div class="assignee-member-list">
                            <?php foreach ($__members as $m): ?>
                            <label class="assignee-member-check">
                                <input type="checkbox" name="assignee_user_ids[]" value="<?= (int)$m['user_id'] ?>"
                                       <?= in_array((int)$m['user_id'], $_aUserIds) ? 'checked' : '' ?>>
                                <?= Helper::avatar(['username' => $m['username'], 'avatar' => $m['avatar'] ?? null, 'id' => $m['user_id']], 22) ?>
                                <span><?= Helper::e($m['username']) ?></span>
                            </label>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                        <!-- Project externals with email (portal access) -->
                        <?php if (!empty($_projExtWithEmail)): ?>
                        <div class="assignee-member-list" style="margin-top:6px;padding-top:6px;border-top:1px solid var(--border)">
                            <div class="ext-section-label"><?= t('external_participants') ?></div>
                            <?php foreach ($_projExtWithEmail as $pe): ?>
                            <label class="assignee-member-check">
                                <input type="checkbox" name="assignee_external_ids[]" value="<?= (int)$pe['id'] ?>"
                                       <?= in_array((int)$pe['id'], $_aExtIds) ? 'checked' : '' ?>>
                                <span class="avatar-initials avatar-ext" style="width:22px;height:22px;font-size:9px"><?= Helper::e(mb_strtoupper(mb_substr($pe['name'],0,1))) ?></span>
                                <span><?= Helper::e($pe['name']) ?></span>
                                <span class="badge-ext" style="font-size:10px"><?= Helper::e($pe['email']) ?></span>
                            </label>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                        <!-- Dummy names: project-level placeholders + ad-hoc free text -->
                        <div class="ext-assignee-section" style="margin-top:8px;padding-top:8px;border-top:1px solid var(--border)">
                            <div class="ext-section-label"><?= t('dummy_assignees') ?></div>
                            <?php if (!empty($_projDummies)): ?>
                            <div class="assignee-member-list" style="margin-bottom:6px">
                                <?php foreach ($_projDummies as $pd): ?>
                                <label class="assignee-member-check">
                                    <input type="checkbox" name="assignee_external_ids[]" value="<?= (int)$pd['id'] ?>"
                                           <?= in_array((int)$pd['id'], $_aExtIds) ? 'checked' : '' ?>>
                                    <span class="avatar-initials avatar-ext" style="width:22px;height:22px;font-size:9px"><?= Helper::e(mb_strtoupper(mb_substr($pd['name'],0,1))) ?></span>
                                    <span><?= Helper::e($pd['name']) ?></span>
                                </label>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                            <div id="detailExtAssigneeList">
                                <?php foreach ($_aDummies as $ext): ?>
                                <div class="ext-assignee-tag">
                                    <input type="hidden" name="assignee_external_names[]" value="<?= Helper::e($ext) ?>">
                                    <span class="avatar-initials avatar-ext" style="width:20px;height:20px;font-size:8px"><?= Helper::e(mb_strtoupper(mb_substr($ext,0,1))) ?></span>
                                    <span><?= Helper::e($ext) ?></span>
                                    <button type="button" data-remove-parent class="ext-tag-remove">×</button>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="ext-add-row" style="margin-top:6px">
                                <input type="text" id="detailExtNameInput" class="form-input form-input-sm"
                                       placeholder="<?= t('external_name_placeholder') ?>"
                                       data-keydown="detailExtAssigneeKeydown">
                                <button type="button" class="btn btn-ghost btn-sm" data-click="addDetailExtAssignee">+ <?= t('add') ?></button>
                            </div>
                        </div>
                    </div>
                    <div class="dep-form-actions">
                        <button type="submit" class="btn btn-primary btn-sm"><?= t('save') ?></button>
                        <button type="button" class="btn btn-ghost btn-sm" data-click="closeAssigneeForm"><?= t('cancel') ?></button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>

        <!-- Predecessors & Successors -->
        <?php if (in_array($myRole, ['owner','manager','member']) && !empty($allProjectTasks)): ?>
        <div class="card">
            <div class="card-header">
                <h2 class="card-title"><?= t('predecessors') ?> &amp; <?= t('successors') ?></h2>
                <button type="button" class="dep-toggle-btn" id="depToggleBtn" data-click="toggleDepForm">
                    <?= t('edit') ?>
                </button>
            </div>

            <!-- Read-only view -->
            <div id="depReadView" class="card-body dep-card">
                <?php
                $predecessorIds_view = array_column($predecessors, 'id');
                $successorIds_view   = array_column($successors, 'id');
                ?>
                <div class="dep-section">
                    <span class="dep-label"><?= t('predecessors') ?></span>
                    <?php if (empty($predecessors)): ?>
                    <span class="dep-none" data-click="openDepForm"><?= t('no_predecessors') ?></span>
                    <?php else: ?>
                    <?php foreach ($predecessors as $pre): ?>
                    <a href="/task/<?= $pre['id'] ?>" class="dep-item">
                        <span class="status-dot" style="background:<?= Helper::e($pre['status_color'] ?? '#6b7280') ?>"></span>
                        <span class="dep-title"><?= Helper::e($pre['title']) ?></span>
                    </a>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <div class="dep-section dep-section--sep">
                    <span class="dep-label"><?= t('successors') ?></span>
                    <?php if (empty($successors)): ?>
                    <span class="dep-none" data-click="openDepForm"><?= t('no_successors') ?></span>
                    <?php else: ?>
                    <?php foreach ($successors as $suc): ?>
                    <a href="/task/<?= $suc['id'] ?>" class="dep-item">
                        <span class="status-dot" style="background:<?= Helper::e($suc['status_color'] ?? '#6b7280') ?>"></span>
                        <span class="dep-title"><?= Helper::e($suc['title']) ?></span>
                    </a>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Edit form (hidden by default) -->
            <div id="depEditView" class="dep-edit-view" style="display:none">
                <form method="POST" action="/task/<?= $task['id'] ?>/edit">
                    <?= Helper::csrf() ?>
                    <input type="hidden" name="action" value="update_dependencies">
                    <div class="dep-form-body">
                        <div class="dep-form-group">
                            <label class="dep-form-label"><?= t('predecessors') ?></label>
                            <select name="predecessors[]" class="form-select dep-select" multiple
                                    id="predSelect" size="<?= min(count($allProjectTasks) + 1, 6) ?>">
                                <option value="0" class="dep-none-opt"
                                        <?= empty($predecessors) ? 'selected' : '' ?>>
                                    — <?= t('no_predecessors') ?> —
                                </option>
                                <?php foreach ($allProjectTasks as $pt): ?>
                                <option value="<?= $pt['id'] ?>"
                                        <?= in_array((int)$pt['id'], $predecessorIds_view) ? 'selected' : '' ?>>
                                    <?= Helper::e($pt['title']) ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="dep-form-group">
                            <label class="dep-form-label"><?= t('successors') ?></label>
                            <select name="successors[]" class="form-select dep-select" multiple
                                    id="succSelect" size="<?= min(count($allProjectTasks) + 1, 6) ?>">
                                <option value="0" class="dep-none-opt"
                                        <?= empty($successors) ? 'selected' : '' ?>>
                                    — <?= t('no_successors') ?> —
                                </option>
                                <?php foreach ($allProjectTasks as $pt): ?>
                                <option value="<?= $pt['id'] ?>"
                                        <?= in_array((int)$pt['id'], $successorIds_view) ? 'selected' : '' ?>>
                                    <?= Helper::e($pt['title']) ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="dep-form-hint"><?= t('predecessors_hint') ?></div>
                    <div class="dep-form-actions">
                        <button type="submit" class="btn btn-primary btn-sm"><?= t('save') ?></button>
                        <button type="button" class="btn btn-ghost btn-sm" data-click="closeDepForm"><?= t('cancel') ?></button>
                    </div>
                </form>
            </div>
        </div>
        <?php elseif (!empty($predecessors) || !empty($successors)): ?>
        <!-- Guest / read-only view when no editing allowed -->
        <div class="card">
            <div class="card-body dep-card">
                <?php if (!empty($predecessors)): ?>
                <div class="dep-section">
                    <span class="dep-label"><?= t('predecessors') ?></span>
                    <?php foreach ($predecessors as $pre): ?>
                    <a href="/task/<?= $pre['id'] ?>" class="dep-item">
                        <span class="status-dot" style="background:<?= Helper::e($pre['status_color'] ?? '#6b7280') ?>"></span>
                        <span class="dep-title"><?= Helper::e($pre['title']) ?></span>
                    </a>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
                <?php if (!empty($successors)): ?>
                <div class="dep-section <?= !empty($predecessors) ? 'dep-section--sep' : '' ?>">
                    <span class="dep-label"><?= t('successors') ?></span>
                    <?php foreach ($successors as $suc): ?>
                    <a href="/task/<?= $suc['id'] ?>" class="dep-item">
                        <span class="status-dot" style="background:<?= Helper::e($suc['status_color'] ?? '#6b7280') ?>"></span>
                        <span class="dep-title"><?= Helper::e($suc['title']) ?></span>
                    </a>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>


        <!-- Upload attachment -->
        <?php if (in_array($myRole, ['owner','manager','member'])): ?>
        <div class="card">
            <div class="card-header"><h2 class="card-title"><?= t('upload_file') ?></h2></div>
            <div class="card-body">
                <form method="POST" action="/task/<?= $task['id'] ?>/edit" enctype="multipart/form-data">
                    <?= Helper::csrf() ?>
                    <input type="hidden" name="action" value="upload_only">
                    <input type="hidden" name="title" value="<?= Helper::e($task['title']) ?>">
                    <input type="hidden" name="status_id" value="<?= $task['status_id'] ?>">
                    <input type="hidden" name="priority" value="<?= $task['priority'] ?>">
                    <input type="file" name="attachment" class="form-file" required>
                    <button type="submit" class="btn btn-ghost btn-sm mt-2"><?= t('upload_file') ?></button>
                </form>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php
function renderHtmlContent(string $content): string {
    if (strpos($content, '<') === false) {
        $enc = htmlspecialchars($content, ENT_QUOTES, 'UTF-8');
        $enc = preg_replace_callback('/@\[([^\]]+)\]/', fn($m) => '<span class="mention">@' . $m[1] . '</span>', $enc);
        return nl2br($enc);
    }
    return $content; // already sanitized on save
}
// keep backward compat alias
function renderMentions(string $t): string { return renderHtmlContent($t); }
?>
<script nonce="<?= csp_nonce() ?>" src="/assets/js/richeditor.js"></script>
<style>
.re-toolbar{display:flex;align-items:center;gap:2px;padding:4px 6px;background:var(--bg-base);border:1px solid var(--border-color);border-bottom:none;border-radius:var(--border-radius-sm) var(--border-radius-sm) 0 0;flex-wrap:wrap}
.re-btn{background:none;border:1px solid transparent;border-radius:3px;cursor:pointer;padding:3px 6px;font-size:.8rem;color:var(--text-primary);line-height:1;display:inline-flex;align-items:center;justify-content:center}
.re-btn:hover{background:var(--bg-hover);border-color:var(--border-color)}
.re-sep{width:1px;height:16px;background:var(--border-color);margin:0 3px}
.re-editor{border:1px solid var(--border-color);border-radius:0 0 var(--border-radius-sm) var(--border-radius-sm);padding:8px 10px;font-size:.875rem;outline:none;overflow-y:auto;line-height:1.5;color:var(--text-primary);background:var(--bg-card)}
.re-editor:empty::before{content:attr(data-placeholder);color:var(--text-muted);pointer-events:none}
.re-editor:focus{border-color:var(--primary)}
.rich-content table{border-collapse:collapse;width:100%;margin:8px 0}
.rich-content td,.rich-content th{border:1px solid var(--border-color);padding:6px 10px;min-width:60px}
.rich-content img{max-width:100%;height:auto;border-radius:4px;margin:4px 0}
.rich-content p{margin:.4em 0}
.re-editor table{border-collapse:collapse;width:100%;margin:8px 0}
.re-editor td,.re-editor th{border:1px solid var(--border-color);padding:6px 10px;min-width:60px}
.re-editor img{max-width:100%;height:auto;border-radius:4px;margin:4px 0}
.re-editor p{margin:.4em 0}
.mention-dropdown{position:fixed;z-index:9999;background:var(--bg-card);border:1px solid var(--border-color);border-radius:var(--border-radius-sm);box-shadow:0 4px 16px rgba(0,0,0,.12);min-width:220px;max-height:220px;overflow-y:auto;display:none}
.mention-item{display:flex;align-items:center;gap:8px;padding:7px 12px;cursor:pointer;font-size:.875rem;color:var(--text-primary)}
.mention-item:hover,.mention-item.active{background:var(--bg-hover)}
.mention-item-badge{font-size:.68rem;background:#fef3c7;color:#b45309;border-radius:3px;padding:1px 4px;margin-left:auto}
.mention{display:inline;background:#eff6ff;color:#1d4ed8;border-radius:3px;padding:1px 3px;font-weight:500;font-size:.9em}
</style>
<script nonce="<?= csp_nonce() ?>">
window.addEventListener('DOMContentLoaded', () => {
    const commentForm = document.querySelector('.comment-form');
    if (!commentForm) return;
    const mentionData = <?= !empty($mentionData) ? json_encode(array_values($mentionData)) : '[]' ?>;
    initRichEditor('comment-editor', 'comment-hidden', {
        placeholder: '<?= addslashes(t('comment_placeholder')) ?> – @ zum Erwähnen',
        minHeight: 80,
        mentionData: mentionData
    });
});

document.querySelectorAll('.comment-delete-btn').forEach(btn => {
    btn.addEventListener('click', async () => {
        if (!confirm('<?= t('confirm_delete') ?>')) return;
        const res = await fetch('/api/comment/delete', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({comment_id: btn.dataset.id, csrf_token: CSRF_TOKEN})
        });
        if (res.ok) btn.closest('.comment').remove();
    });
});

// ── Dependency form toggle ────────────────────────────────────
function toggleDepForm() {
    const rv = document.getElementById('depReadView');
    const ev = document.getElementById('depEditView');
    if (!rv || !ev) return;
    const isOpen = ev.style.display !== 'none';
    isOpen ? closeDepForm() : openDepForm();
}
function openDepForm() {
    const rv = document.getElementById('depReadView');
    const ev = document.getElementById('depEditView');
    const btn = document.getElementById('depToggleBtn');
    if (rv) rv.style.display = 'none';
    if (ev) ev.style.display = '';
    if (btn) btn.textContent = '<?= t('cancel') ?>';
}
function closeDepForm() {
    const rv = document.getElementById('depReadView');
    const ev = document.getElementById('depEditView');
    const btn = document.getElementById('depToggleBtn');
    if (rv) rv.style.display = '';
    if (ev) ev.style.display = 'none';
    if (btn) btn.textContent = '<?= t('edit') ?>';
}

// ── Assignee form toggle ──────────────────────────────────────
function toggleAssigneeForm() {
    var rv = document.getElementById('assigneeReadView');
    var ev = document.getElementById('assigneeEditView');
    if (!rv || !ev) return;
    if (ev.style.display === 'none') {
        rv.style.display = 'none';
        ev.style.display = '';
        document.getElementById('assigneeToggleBtn').textContent = '<?= t('cancel') ?>';
    } else {
        closeAssigneeForm();
    }
}
function closeAssigneeForm() {
    var rv = document.getElementById('assigneeReadView');
    var ev = document.getElementById('assigneeEditView');
    var btn = document.getElementById('assigneeToggleBtn');
    if (rv) rv.style.display = '';
    if (ev) ev.style.display = 'none';
    if (btn) btn.textContent = '<?= t('edit') ?>';
}
function detailExtAssigneeKeydown(el, e) {
    if (e.key === 'Enter') { e.preventDefault(); addDetailExtAssignee(); }
}
function prioritySubmit(el) {
    el.className = 'meta-select priority-meta-select priority-' + el.value;
    el.form.submit();
}
function addDetailExtAssignee() {
    var input = document.getElementById('detailExtNameInput');
    var name  = input.value.trim();
    if (!name) return;
    var list = document.getElementById('detailExtAssigneeList');
    var div  = document.createElement('div');
    div.className = 'ext-assignee-tag';
    var safeVal = name.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    var initial = name.charAt(0).toUpperCase();
    div.innerHTML =
        '<input type="hidden" name="assignee_external_names[]" value="' + safeVal + '">' +
        '<span class="avatar-initials avatar-ext" style="width:20px;height:20px;font-size:8px">' + initial + '</span>' +
        '<span>' + safeVal + '</span>' +
        '<button type="button" data-remove-parent class="ext-tag-remove">×</button>';
    list.appendChild(div);
    input.value = '';
    input.focus();
}

// "Kein Vorgänger/Nachfolger" option: selecting it deselects all others, and vice versa
function initDepSelect(selectId) {
    const sel = document.getElementById(selectId);
    if (!sel) return;
    sel.addEventListener('mousedown', (e) => {
        if (!(e.target instanceof HTMLOptionElement)) return;
        const clickedNone = e.target.value === '0';
        if (clickedNone) {
            // Let the click happen, then deselect all non-none options
            setTimeout(() => {
                [...sel.options].forEach(o => { if (o.value !== '0') o.selected = false; });
            }, 0);
        } else {
            // Deselect the "none" option
            setTimeout(() => {
                const noneOpt = [...sel.options].find(o => o.value === '0');
                if (noneOpt) noneOpt.selected = false;
            }, 0);
        }
    });
}
initDepSelect('predSelect');
initDepSelect('succSelect');


</script>
