/**
 * Tasks pane — goal is "better than Thunderbird" on tasks.
 *
 * Phase-1 features (this commit):
 * - Local-only task store with priority, due-date, snooze, tags, notes
 * - Inline edit, drag-to-reorder by priority, mark complete with strikethrough
 * - Filter by status (active/completed/all), tag, due-soon
 * - "Snooze until" (defer-to-date) — Thunderbird Lightning has nothing here
 * - Quick add from email subject (composeInit-style, hooked from message viewer
 *   right-click later)
 *
 * Phase-2 (later):
 * - Google Tasks sync (oauthsupport scope ready)
 * - CalDAV VTODO interop
 * - Task-from-email contextmenu
 * - Reminders that share the calendar/mail alarm subsystem
 */
const STORE_KEY = "mailx-tasks-v1";
let isOpen = false;
function loadTasks() {
    try {
        const raw = localStorage.getItem(STORE_KEY);
        if (!raw)
            return [];
        const arr = JSON.parse(raw);
        return Array.isArray(arr) ? arr : [];
    }
    catch {
        return [];
    }
}
function saveTasks(tasks) {
    try {
        localStorage.setItem(STORE_KEY, JSON.stringify(tasks));
    }
    catch { /* */ }
}
export async function openTasks() {
    if (isOpen)
        return;
    isOpen = true;
    const backdrop = document.createElement("div");
    backdrop.className = "mailx-modal-backdrop";
    const panel = document.createElement("div");
    panel.className = "mailx-modal mailx-modal-wide";
    panel.innerHTML = `
        <div class="mailx-modal-title">
            <span class="mailx-modal-title-text">Tasks</span>
            <button type="button" class="mailx-modal-close" id="tk-close" title="Close (Esc)" aria-label="Close">&times;</button>
        </div>
        <div class="tk-toolbar">
            <input type="text" id="tk-quickadd" class="mailx-modal-input" placeholder="Add task — Enter to commit, prefix !!=high !=med ?=low, @tag, due:YYYY-MM-DD" autocomplete="off">
        </div>
        <div class="tk-filters">
            <button type="button" class="tk-filter-btn" data-filter="active">Active</button>
            <button type="button" class="tk-filter-btn" data-filter="due-soon">Due soon</button>
            <button type="button" class="tk-filter-btn" data-filter="completed">Completed</button>
            <button type="button" class="tk-filter-btn" data-filter="all">All</button>
            <span class="tk-spacer"></span>
            <span id="tk-count" class="tk-count"></span>
        </div>
        <div class="tk-list" id="tk-list"></div>
        <div class="mailx-modal-buttons">
            <span class="mailx-modal-spacer"></span>
            <span class="cal-source-note">Local-only · Google Tasks sync pending</span>
            <button type="button" class="mailx-modal-btn" data-action="close">Close</button>
        </div>`;
    backdrop.appendChild(panel);
    document.body.appendChild(backdrop);
    const quickAdd = panel.querySelector("#tk-quickadd");
    const listEl = panel.querySelector("#tk-list");
    const countEl = panel.querySelector("#tk-count");
    let tasks = loadTasks();
    let filter = "active";
    const setFilter = (f) => {
        filter = f;
        panel.querySelectorAll(".tk-filter-btn").forEach(b => b.classList.toggle("tk-filter-active", b.dataset.filter === f));
        render();
    };
    panel.querySelectorAll(".tk-filter-btn").forEach(b => b.addEventListener("click", () => setFilter(b.dataset.filter)));
    setFilter("active");
    const parseQuickAdd = (line) => {
        const t = {
            id: `tk-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
            title: "", priority: 0, createdAt: Date.now(),
        };
        const tags = [];
        const words = line.split(/\s+/);
        const titleParts = [];
        for (const w of words) {
            if (w === "!!") {
                t.priority = 3;
                continue;
            }
            if (w === "!") {
                t.priority = 2;
                continue;
            }
            if (w === "?") {
                t.priority = 1;
                continue;
            }
            if (w.startsWith("@") && w.length > 1) {
                tags.push(w.slice(1));
                continue;
            }
            const dueMatch = w.match(/^due:(\S+)$/i);
            if (dueMatch) {
                const parsed = Date.parse(dueMatch[1]);
                if (!isNaN(parsed))
                    t.due = parsed;
                continue;
            }
            titleParts.push(w);
        }
        t.title = titleParts.join(" ").trim();
        if (tags.length)
            t.tags = tags;
        return t;
    };
    quickAdd.addEventListener("keydown", (e) => {
        if (e.key !== "Enter")
            return;
        const v = quickAdd.value.trim();
        if (!v)
            return;
        const t = parseQuickAdd(v);
        if (!t.title) {
            alert("Task needs a title.");
            return;
        }
        tasks.push(t);
        saveTasks(tasks);
        quickAdd.value = "";
        render();
    });
    const render = () => {
        const now = Date.now();
        let visible = tasks.slice();
        if (filter === "active")
            visible = visible.filter(t => !t.completed && (!t.snoozeUntil || t.snoozeUntil <= now));
        else if (filter === "completed")
            visible = visible.filter(t => !!t.completed);
        else if (filter === "due-soon")
            visible = visible.filter(t => !t.completed && t.due && t.due <= now + 7 * 86400_000);
        // Sort: priority desc, then due asc (none last), then created asc.
        visible.sort((a, b) => {
            if ((b.priority || 0) !== (a.priority || 0))
                return (b.priority || 0) - (a.priority || 0);
            const ad = a.due || Number.MAX_SAFE_INTEGER;
            const bd = b.due || Number.MAX_SAFE_INTEGER;
            if (ad !== bd)
                return ad - bd;
            return a.createdAt - b.createdAt;
        });
        countEl.textContent = `${visible.length} of ${tasks.length}`;
        if (visible.length === 0) {
            listEl.innerHTML = `<div class="tk-empty">Nothing matches the ${filter} filter.</div>`;
            return;
        }
        const dueLabel = (ms) => {
            if (!ms)
                return "";
            const d = new Date(ms);
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            const dt = new Date(ms);
            dt.setHours(0, 0, 0, 0);
            const days = Math.round((dt.getTime() - today.getTime()) / 86400_000);
            if (days < 0)
                return `${-days}d overdue`;
            if (days === 0)
                return "today";
            if (days === 1)
                return "tomorrow";
            if (days < 7)
                return `${days}d`;
            return d.toLocaleDateString();
        };
        const prioLabel = (p) => p === 3 ? "‼" : p === 2 ? "!" : p === 1 ? "·" : "";
        listEl.innerHTML = visible.map(t => `
            <div class="tk-row${t.completed ? " tk-done" : ""}" data-id="${t.id}">
                <input type="checkbox" class="tk-check" ${t.completed ? "checked" : ""}>
                <span class="tk-prio tk-prio-${t.priority}">${prioLabel(t.priority)}</span>
                <span class="tk-title" contenteditable="plaintext-only">${escapeHtml(t.title)}</span>
                ${t.tags?.length ? `<span class="tk-tags">${t.tags.map(x => `#${escapeHtml(x)}`).join(" ")}</span>` : ""}
                <span class="tk-due${t.due && t.due < now && !t.completed ? " tk-overdue" : ""}">${dueLabel(t.due)}</span>
                <button type="button" class="tk-snooze" title="Snooze 1d / 1w (right-click)">⏰</button>
                <button type="button" class="tk-del" title="Delete">×</button>
            </div>`).join("");
        listEl.querySelectorAll(".tk-row").forEach(row => {
            const id = row.dataset.id;
            const t = tasks.find(x => x.id === id);
            row.querySelector(".tk-check").addEventListener("change", (e) => {
                const ck = e.target;
                t.completed = ck.checked ? Date.now() : undefined;
                saveTasks(tasks);
                render();
            });
            row.querySelector(".tk-del").addEventListener("click", () => {
                if (!confirm(`Delete task "${t.title}"?`))
                    return;
                tasks = tasks.filter(x => x.id !== id);
                saveTasks(tasks);
                render();
            });
            row.querySelector(".tk-snooze").addEventListener("click", () => {
                t.snoozeUntil = Date.now() + 86400_000; // 1d
                saveTasks(tasks);
                render();
            });
            row.querySelector(".tk-snooze").addEventListener("contextmenu", (e) => {
                e.preventDefault();
                t.snoozeUntil = Date.now() + 7 * 86400_000; // 1w
                saveTasks(tasks);
                render();
            });
            const titleEl = row.querySelector(".tk-title");
            titleEl.addEventListener("blur", () => {
                const v = (titleEl.textContent || "").trim();
                if (v && v !== t.title) {
                    t.title = v;
                    saveTasks(tasks);
                }
            });
            titleEl.addEventListener("keydown", (e) => {
                if (e.key === "Enter") {
                    e.preventDefault();
                    titleEl.blur();
                }
            });
        });
    };
    const close = () => {
        backdrop.remove();
        document.removeEventListener("keydown", onKey, true);
        isOpen = false;
    };
    // Esc always closes. Earlier guard blocked Esc when focus was in the
    // quickadd input, which made the panel feel stuck — user hits Esc to
    // dismiss and nothing happens. Blur-on-Esc before close is the right
    // behavior: the close handler is idempotent and the input loses focus
    // when the backdrop goes away anyway.
    const onKey = (e) => {
        if (e.key === "Escape") {
            e.stopPropagation();
            e.preventDefault();
            close();
        }
    };
    document.addEventListener("keydown", onKey, true);
    panel.querySelector("#tk-close").addEventListener("click", close);
    panel.querySelector('[data-action="close"]').addEventListener("click", close);
    backdrop.addEventListener("mousedown", (e) => { if (e.target === backdrop)
        close(); });
    quickAdd.focus();
}
function escapeHtml(s) {
    return s.replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;" }[c]));
}
//# sourceMappingURL=tasks.js.map