/**
 * Folder picker — small modal for choosing a destination folder.
 * Used by the message-list right-click "Move to folder…" item and any
 * other UI that needs the user to pick a folder.
 *
 * Reads folders from the local DB via getFolders() (local-first — no
 * server round-trip). Filters by typed text. Returns the selected
 * folder, or null if the user dismissed.
 */

import { getFolders } from "../lib/api-client.js";

export interface FolderPickResult {
    accountId: string;
    folderId: number;
    folderPath: string;
    folderName: string;
}

/** Show a modal folder picker. Returns a promise resolving to the picked
 *  folder, or null if dismissed. The list is restricted to one account
 *  (the current message's account) so it doesn't get cluttered with
 *  unrelated folders; cross-account moves can be added later via an
 *  account selector at the top of the picker. */
export function pickFolder(accountId: string, opts?: { excludeFolderIds?: number[]; title?: string }): Promise<FolderPickResult | null> {
    return new Promise(async (resolve) => {
        const overlay = document.createElement("div");
        overlay.className = "folder-picker-overlay";
        overlay.style.cssText = "position:fixed;inset:0;background:rgba(0,0,0,0.4);z-index:10000;display:flex;align-items:center;justify-content:center;";

        const modal = document.createElement("div");
        modal.className = "folder-picker-modal";
        modal.style.cssText = "background:var(--bg, #fff);color:var(--fg, #000);border:1px solid var(--border, #ccc);border-radius:6px;box-shadow:0 4px 24px rgba(0,0,0,0.3);width:380px;max-width:90vw;max-height:70vh;display:flex;flex-direction:column;overflow:hidden;";

        const header = document.createElement("div");
        header.style.cssText = "padding:10px 14px;border-bottom:1px solid var(--border, #ddd);font-weight:600;";
        header.textContent = opts?.title || "Move to folder…";
        modal.appendChild(header);

        const search = document.createElement("input");
        search.type = "text";
        search.placeholder = "Filter folders…";
        search.style.cssText = "margin:8px 12px;padding:6px 10px;border:1px solid var(--border, #ccc);border-radius:4px;font-size:13px;";
        modal.appendChild(search);

        const listEl = document.createElement("div");
        listEl.style.cssText = "flex:1;overflow-y:auto;padding:4px 0;";
        modal.appendChild(listEl);

        const footer = document.createElement("div");
        footer.style.cssText = "padding:8px 12px;border-top:1px solid var(--border, #ddd);display:flex;justify-content:flex-end;gap:8px;";
        const cancelBtn = document.createElement("button");
        cancelBtn.textContent = "Cancel";
        cancelBtn.style.cssText = "padding:6px 14px;cursor:pointer;";
        footer.appendChild(cancelBtn);
        modal.appendChild(footer);

        overlay.appendChild(modal);
        document.body.appendChild(overlay);

        const dismiss = (result: FolderPickResult | null) => {
            overlay.remove();
            document.removeEventListener("keydown", onKey);
            resolve(result);
        };
        const onKey = (e: KeyboardEvent) => {
            if (e.key === "Escape") { e.preventDefault(); dismiss(null); }
            if (e.key === "Enter") {
                const first = listEl.querySelector(".folder-picker-row.match") as HTMLElement | null;
                if (first) first.click();
            }
        };
        document.addEventListener("keydown", onKey);
        overlay.addEventListener("click", (e) => { if (e.target === overlay) dismiss(null); });
        cancelBtn.addEventListener("click", () => dismiss(null));

        // Local-first: load from DB synchronously-ish (one IPC round-trip).
        let folders: any[] = [];
        try {
            folders = (await getFolders(accountId)) || [];
        } catch (e) {
            listEl.textContent = "Failed to load folders";
            return;
        }

        // Hide special-use that don't make sense as targets (Outbox).
        // Allow Trash / Junk so users can manually file into them.
        const excluded = new Set(opts?.excludeFolderIds || []);
        const targets = folders
            .filter((f: any) => !excluded.has(f.id))
            .filter((f: any) => f.specialUse !== "outbox")
            .sort((a: any, b: any) => a.path.localeCompare(b.path));

        function render(filter: string): void {
            listEl.innerHTML = "";
            const lc = filter.toLowerCase().trim();
            let firstMatchSet = false;
            for (const f of targets) {
                const row = document.createElement("div");
                row.className = "folder-picker-row";
                row.style.cssText = "padding:6px 14px;cursor:pointer;font-size:13px;display:flex;justify-content:space-between;gap:8px;";
                const name = document.createElement("span");
                name.textContent = f.path;
                const tag = document.createElement("span");
                tag.style.cssText = "color:var(--muted, #888);font-size:11px;";
                tag.textContent = f.specialUse || "";
                row.appendChild(name);
                row.appendChild(tag);
                const matches = !lc || f.path.toLowerCase().includes(lc);
                if (matches) {
                    row.classList.add("match");
                    if (!firstMatchSet) { row.style.background = "var(--hover, #eee)"; firstMatchSet = true; }
                }
                row.addEventListener("mouseenter", () => row.style.background = "var(--hover, #eee)");
                row.addEventListener("mouseleave", () => row.style.background = "");
                row.addEventListener("click", () => {
                    dismiss({ accountId, folderId: f.id, folderPath: f.path, folderName: f.path.split(/[./]/).pop() || f.path });
                });
                if (!matches) row.style.display = "none";
                listEl.appendChild(row);
            }
        }
        render("");
        search.addEventListener("input", () => render(search.value));
        setTimeout(() => search.focus(), 0);
    });
}
