<?php $pageTitle = t('tasks'); ?>

<div class="page-header">
    <div class="page-header-left">
        <a href="/dashboard" class="btn btn-ghost btn-sm">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
            <?= t('dashboard') ?>
        </a>
        <h1 class="page-title"><?= t('tasks') ?></h1>
    </div>
    <div class="page-header-actions">
        <span class="text-muted" style="font-size:.85rem">
            <?= count($tasks) ?> <?= t('tasks') ?>
        </span>
    </div>
</div>

<!-- Filters -->
<?php
    $_meId    = (string)Auth::id();
    $_meValue = 'u_' . $_meId;
    $_assigned = (string)($filterAssigned ?? '');
    if (ctype_digit($_assigned)) $_assigned = 'u_' . $_assigned;   // legacy plain id from dashboard cards
    if ($_assigned === '')       $_assigned = $_meValue;
    $_assignedDisplay = (string)($assignedDisplay ?? t('assigned_filter_me'));
?>
<form method="GET" action="/my-tasks" class="filter-bar" id="myTasksFilterForm">
    <div class="assignee-picker">
        <input type="hidden" name="assigned_to" id="assignedToValue" value="<?= Helper::e($_assigned) ?>">
        <input type="text" id="assignedToDisplay" class="form-input filter-select" autocomplete="off"
               value="<?= Helper::e($_assignedDisplay) ?>" placeholder="<?= t('assigned_filter_me') ?>">
        <div id="assignedToDropdown" class="assignee-dropdown" style="display:none"></div>
    </div>
    <select name="status" class="form-select filter-select" data-auto-submit>
        <option value="open"  <?= $filterStatus === 'open'  ? 'selected' : '' ?>><?= t('open_tasks') ?></option>
        <option value="done"  <?= $filterStatus === 'done'  ? 'selected' : '' ?>><?= t('done_tasks') ?></option>
        <option value="all"   <?= $filterStatus === 'all'   ? 'selected' : '' ?>><?= t('all_tasks') ?></option>
    </select>
    <select name="priority" class="form-select filter-select" data-auto-submit>
        <option value=""><?= t('priority') ?>: <?= t('all') ?></option>
        <?php foreach (['urgent','high','medium','low'] as $p): ?>
        <option value="<?= $p ?>" <?= $filterPriority === $p ? 'selected' : '' ?>><?= t('priority_' . $p) ?></option>
        <?php endforeach; ?>
    </select>
    <?php if (!empty($myProjects)): ?>
    <select name="project_id" class="form-select filter-select" data-auto-submit>
        <option value=""><?= t('projects') ?>: <?= t('all') ?></option>
        <?php foreach ($myProjects as $proj): ?>
        <option value="<?= $proj['id'] ?>" <?= $filterProject == $proj['id'] ? 'selected' : '' ?>>
            <?= Helper::e($proj['name']) ?>
        </option>
        <?php endforeach; ?>
    </select>
    <?php endif; ?>
    <select name="due" class="form-select filter-select" data-auto-submit>
        <option value=""><?= t('due_date') ?>: <?= t('all') ?></option>
        <option value="today"   <?= ($filterDue ?? '') === 'today'   ? 'selected' : '' ?>><?= t('due_today') ?></option>
        <option value="overdue" <?= ($filterDue ?? '') === 'overdue' ? 'selected' : '' ?>><?= t('overdue') ?></option>
    </select>
    <?php $_anyFilterActive = $filterStatus !== 'open' || $filterPriority || $filterProject || !empty($filterDue) || $_assigned !== $_meValue; ?>
    <?php if ($_anyFilterActive): ?>
    <a href="/my-tasks" class="btn btn-ghost btn-sm">✕ <?= t('reset') ?></a>
    <?php endif; ?>
    <a href="/my-tasks?clear=1" class="btn btn-ghost btn-sm" title="<?= t('clear_filters_hint') ?>"><?= t('clear_filters') ?></a>
</form>

<?php if (empty($tasks)): ?>
<div class="empty-state">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="64" height="64" opacity=".3">
        <path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/>
    </svg>
    <h3><?= t('no_tasks') ?></h3>
    <p class="text-muted"><?= t('my_tasks_empty') ?></p>
</div>
<?php else: ?>

<?php foreach ($grouped as $group): ?>
<?php $proj = $group['project']; $groupTasks = $group['tasks']; ?>
<div class="my-tasks-group">
    <div class="my-tasks-group-header">
        <a href="/project/<?= $proj['id'] ?>" class="my-tasks-project-link">
            <span class="project-dot" style="background:<?= Helper::e($proj['color']) ?>"></span>
            <?= Helper::e($proj['name']) ?>
        </a>
        <span class="task-count-badge"><?= count($groupTasks) ?></span>
    </div>
    <div class="table-card" style="margin-top:0;border-radius:0 0 var(--border-radius) var(--border-radius)">
        <table class="data-table">
            <thead>
                <tr>
                    <th><?= t('task_title') ?></th>
                    <th><?= t('task_status') ?></th>
                    <th><?= t('priority') ?></th>
                    <th><?= t('due_date') ?></th>
                    <th><?= t('assigned_to') ?></th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($groupTasks as $task): ?>
            <tr class="table-row-link <?= $task['is_done'] ? 'task-row-done' : '' ?>" data-href="/task/<?= $task['id'] ?>">
                <td>
                    <a href="/task/<?= $task['id'] ?>" class="task-link <?= $task['is_done'] ? 'task-link-done' : '' ?>">
                        <?= Helper::e($task['title']) ?>
                    </a>
                </td>
                <td>
                    <span class="status-badge" style="--status-color:<?= Helper::e($task['status_color']) ?>">
                        <?= Helper::e($task['status_name']) ?>
                    </span>
                </td>
                <td><?= Helper::priorityBadge($task['priority']) ?></td>
                <td>
                    <?php if ($task['due_date']): ?>
                    <?php
                    $dueClass = '';
                    if (!$task['is_done']) {
                        if ($task['due_date'] < date('Y-m-d'))       $dueClass = 'overdue';
                        elseif ($task['due_date'] === date('Y-m-d')) $dueClass = 'due-today';
                    }
                    ?>
                    <span class="task-due <?= $dueClass ?>"><?= Helper::formatDate($task['due_date']) ?></span>
                    <?php else: ?>—<?php endif; ?>
                </td>
                <td><?= Helper::assigneeChips($task['assignees'] ?? [], 20) ?></td>
                <td>
                    <a href="/task/<?= $task['id'] ?>" class="btn btn-ghost btn-xs" data-stop-propagation>
                        →
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endforeach; ?>

<?php endif; ?>

<style>
.assignee-picker { position:relative; min-width:220px }
.assignee-picker .form-input { width:100% }
.assignee-dropdown { position:absolute; top:calc(100% + 3px); left:0; right:0; min-width:240px; background:var(--bg-card,#fff); border:1px solid var(--border-color,#e5e7eb); border-radius:8px; box-shadow:0 4px 16px rgba(0,0,0,.12); max-height:260px; overflow-y:auto; z-index:200; padding:4px 0 }
.assignee-dropdown .ai-section { padding:4px 12px; font-size:.7rem; font-weight:600; color:var(--text-muted,#6b7280); text-transform:uppercase; letter-spacing:.05em }
.assignee-dropdown .ai-item { display:flex; align-items:center; gap:8px; padding:7px 12px; cursor:pointer; font-size:.85rem; color:var(--text-primary,#111) }
.assignee-dropdown .ai-item:hover, .assignee-dropdown .ai-item.active { background:var(--bg-secondary,#f1f5f9) }
.assignee-dropdown .ai-meta { color:var(--text-muted,#6b7280); font-size:.75rem; margin-left:auto }
.assignee-dropdown .ai-empty { padding:12px 14px; color:var(--text-muted,#6b7280); font-size:.85rem; text-align:center }
</style>
<script nonce="<?= csp_nonce() ?>">
(function () {
    'use strict';
    const form     = document.getElementById('myTasksFilterForm');
    const hidden   = document.getElementById('assignedToValue');
    const display  = document.getElementById('assignedToDisplay');
    const dropdown = document.getElementById('assignedToDropdown');
    if (!form || !hidden || !display || !dropdown) return;

    const ME_VALUE  = <?= json_encode($_meValue) ?>;
    const LBL = {
        me:    <?= json_encode(t('assigned_filter_me')) ?>,
        all:   <?= json_encode(t('assigned_filter_anyone')) ?>,
        none:  <?= json_encode(t('assigned_filter_none')) ?>,
        users: <?= json_encode(t('assigned_filter_others')) ?>,
        ext:   <?= json_encode(t('assigned_filter_externals')) ?>,
        empty: <?= json_encode(t('cmdk_empty')) ?>,
    };
    const base = typeof BASE_URL   !== 'undefined' ? BASE_URL   : '';
    const csrf = () => typeof CSRF_TOKEN !== 'undefined' ? CSRF_TOKEN : '';

    let activeIdx   = -1;
    let items       = [];
    let inflight    = null;
    let debounceT   = null;
    let reqSeq      = 0;
    let savedDisplay = display.value;

    function el(tag, attrs, children) {
        const e = document.createElement(tag);
        if (attrs) for (const [k, v] of Object.entries(attrs)) {
            if (v == null || v === false) continue;
            if (k === 'class') e.className = v;
            else e.setAttribute(k, v);
        }
        if (children) for (const c of children) {
            if (c == null) continue;
            e.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
        }
        return e;
    }

    function setActive(idx) {
        items.forEach((node, i) => node.classList.toggle('active', i === idx));
        activeIdx = idx;
        if (idx >= 0 && items[idx]) items[idx].scrollIntoView({block:'nearest'});
    }

    function commit(value, label) {
        hidden.value  = value;
        display.value = label;
        savedDisplay  = label;
        dropdown.style.display = 'none';
        form.submit();
    }

    function defaultsBlock() {
        return [
            { kind:'static', value: ME_VALUE,  label: LBL.me   },
            { kind:'static', value: '__all__', label: LBL.all  },
            { kind:'static', value: '_none',   label: LBL.none },
        ];
    }

    function render(data) {
        dropdown.replaceChildren();
        items = [];
        const q = display.value.trim();

        if (q.length < 2) {
            // Empty / short input → show only the static defaults.
            defaultsBlock().forEach(d => {
                const node = el('div', { class:'ai-item' }, [d.label]);
                node.addEventListener('mousedown', e => { e.preventDefault(); commit(d.value, d.label); });
                node.addEventListener('mouseover', () => setActive(items.indexOf(node)));
                dropdown.appendChild(node);
                items.push(node);
            });
            dropdown.style.display = 'block';
            setActive(0);
            return;
        }

        const users = (data && Array.isArray(data.users))     ? data.users     : [];
        const exts  = (data && Array.isArray(data.externals)) ? data.externals : [];
        if (users.length === 0 && exts.length === 0) {
            dropdown.appendChild(el('div', { class:'ai-empty' }, [LBL.empty]));
            dropdown.style.display = 'block';
            return;
        }

        if (users.length) {
            dropdown.appendChild(el('div', { class:'ai-section' }, [LBL.users]));
            users.forEach(u => {
                const value = 'u_' + parseInt(u.id);
                const meta  = u.email ? el('span', { class:'ai-meta' }) : null;
                if (meta) meta.textContent = String(u.email || '');
                const name  = el('span'); name.textContent = String(u.username || '');
                const node  = el('div', { class:'ai-item' }, [name, meta]);
                node.addEventListener('mousedown', e => { e.preventDefault(); commit(value, String(u.username || '')); });
                node.addEventListener('mouseover', () => setActive(items.indexOf(node)));
                dropdown.appendChild(node);
                items.push(node);
            });
        }
        if (exts.length) {
            dropdown.appendChild(el('div', { class:'ai-section' }, [LBL.ext]));
            exts.forEach(e => {
                const value = 'e_' + parseInt(e.id);
                const meta  = e.project_name ? el('span', { class:'ai-meta' }) : null;
                if (meta) meta.textContent = String(e.project_name || '');
                const name  = el('span'); name.textContent = String(e.name || '');
                const node  = el('div', { class:'ai-item' }, [name, meta]);
                node.addEventListener('mousedown', ev => { ev.preventDefault(); commit(value, String(e.name || '')); });
                node.addEventListener('mouseover', () => setActive(items.indexOf(node)));
                dropdown.appendChild(node);
                items.push(node);
            });
        }
        dropdown.style.display = 'block';
        setActive(0);
    }

    async function search(q) {
        if (q.length < 2) { render(null); return; }
        if (inflight) inflight.abort();
        inflight = new AbortController();
        const seq = ++reqSeq;
        try {
            const res = await fetch(base + '/api/tasks/assignee-search', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ q: q, csrf_token: csrf() }),
                signal: inflight.signal,
            });
            if (!res.ok) { render({ users:[], externals:[] }); return; }
            const data = await res.json();
            if (seq !== reqSeq) return;
            render(data);
        } catch (e) {
            if (e.name !== 'AbortError') render({ users:[], externals:[] });
        }
    }

    function schedule() {
        clearTimeout(debounceT);
        const q = display.value.trim();
        debounceT = setTimeout(() => search(q), 200);
    }

    display.addEventListener('focus', () => { display.select(); render(null); });
    display.addEventListener('input', schedule);
    display.addEventListener('blur',  () => {
        // Restore last committed label so the input never shows a half-typed
        // string after the dropdown closes without selection.
        setTimeout(() => { display.value = savedDisplay; dropdown.style.display = 'none'; }, 150);
    });
    display.addEventListener('keydown', e => {
        if (e.key === 'ArrowDown') { e.preventDefault(); setActive(Math.min(activeIdx + 1, items.length - 1)); }
        else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(Math.max(activeIdx - 1, 0)); }
        else if (e.key === 'Enter') {
            if (items[activeIdx]) { e.preventDefault(); items[activeIdx].dispatchEvent(new MouseEvent('mousedown')); }
        } else if (e.key === 'Escape') { dropdown.style.display = 'none'; display.blur(); }
    });
})();
</script>
