// ==========================================
// NotesPane Kit — QuickSwitcher
// ==========================================
// Cmd+K / Ctrl+K style quick-open overlay.
// Fuzzy title search, keyboard nav, recent notes,
// create-on-enter. Obsidian's signature UX.
// Independently importable.

const { useState, useRef, useCallback, useEffect } = window.hooks;
const html = window.html;

const RECENTS_KEY = 'sw_notes_recent';
const MAX_RECENTS = 5;

function _loadRecents() {
    try {
        return JSON.parse(localStorage.getItem(RECENTS_KEY) || '[]').slice(0, MAX_RECENTS);
    } catch { return []; }
}

function _saveRecent(note) {
    try {
        const recents = _loadRecents().filter(r => r.id !== note.id);
        recents.unshift({ id: note.id, title: note.title, folder_path: note.folder_path });
        localStorage.setItem(RECENTS_KEY, JSON.stringify(recents.slice(0, MAX_RECENTS)));
    } catch {}
}

/**
 * @param {{
 *   open: boolean,
 *   onClose: () => void,
 *   onSelect: (id: string) => void,
 *   onCreateNew: (title: string) => void,
 * }} props
 */
export function QuickSwitcher(props) {
    const { open, onClose, onSelect, onCreateNew } = props;

    const [query, setQuery] = useState('');
    const [results, setResults] = useState([]);
    const [activeIndex, setActiveIndex] = useState(0);
    const [recents, setRecents] = useState([]);
    const inputRef = useRef(null);
    const searchTimerRef = useRef(null);

    // ── Load recents on open ────────────────
    useEffect(() => {
        if (open) {
            setQuery('');
            setResults([]);
            setActiveIndex(0);
            setRecents(_loadRecents());
            setTimeout(() => inputRef.current?.focus(), 50);
        }
    }, [open]);

    // ── Search ──────────────────────────────
    useEffect(() => {
        clearTimeout(searchTimerRef.current);
        if (!query || query.length < 1) {
            setResults([]);
            setActiveIndex(0);
            return;
        }
        searchTimerRef.current = setTimeout(async () => {
            try {
                const resp = await window.sw.api.notes.searchTitles(query, 10);
                setResults(resp || []);
                setActiveIndex(0);
            } catch { setResults([]); }
        }, 150);
    }, [query]);

    // ── Visible items ───────────────────────
    const items = query ? results : recents;
    const hasExactMatch = results.some(r => r.title.toLowerCase() === query.toLowerCase());
    const showCreate = query && !hasExactMatch;

    // ── Keyboard navigation ─────────────────
    const onKeyDown = useCallback((e) => {
        const totalItems = items.length + (showCreate ? 1 : 0);

        if (e.key === 'ArrowDown') {
            e.preventDefault();
            setActiveIndex(i => (i + 1) % Math.max(totalItems, 1));
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            setActiveIndex(i => (i - 1 + totalItems) % Math.max(totalItems, 1));
        } else if (e.key === 'Enter') {
            e.preventDefault();
            if (activeIndex < items.length) {
                _select(items[activeIndex]);
            } else if (showCreate) {
                onCreateNew(query);
                onClose();
            }
        } else if (e.key === 'Escape') {
            e.preventDefault();
            onClose();
        }
    }, [items, activeIndex, showCreate, query, onClose, onCreateNew]);

    const _select = (note) => {
        _saveRecent(note);
        onSelect(note.id);
        onClose();
    };

    if (!open) return null;

    return html`
        <div class="sw-notes-pane__switcher-overlay"
             onClick=${(e) => { if (e.target === e.currentTarget) onClose(); }}>
            <div class="sw-notes-pane__switcher">
                <input class="sw-notes-pane__switcher-input"
                       ref=${inputRef}
                       placeholder="Search notes\u2026"
                       value=${query}
                       onInput=${e => setQuery(e.target.value)}
                       onKeyDown=${onKeyDown} />

                <div class="sw-notes-pane__switcher-results">
                    ${!query && recents.length > 0 && html`
                        <div class="sw-notes-pane__switcher-section">Recent</div>`}

                    ${query && results.length === 0 && html`
                        <div style="padding:12px 14px;color:var(--text-3);font-size:13px">
                            No notes found
                        </div>`}

                    ${items.map((note, i) => html`
                        <div key=${note.id}
                             class=${'sw-notes-pane__switcher-item' + (i === activeIndex ? ' sw-notes-pane__switcher-item--active' : '')}
                             onClick=${() => _select(note)}
                             onMouseEnter=${() => setActiveIndex(i)}>
                            <span class="sw-notes-pane__switcher-item-title">${note.title}</span>
                            ${note.folder_path && note.folder_path !== '/' && html`
                                <span class="sw-notes-pane__switcher-item-folder">${note.folder_path}</span>`}
                        </div>`)}

                    ${showCreate && html`
                        <div class=${'sw-notes-pane__switcher-create' + (activeIndex === items.length ? ' sw-notes-pane__switcher-item--active' : '')}
                             onClick=${() => { onCreateNew(query); onClose(); }}
                             onMouseEnter=${() => setActiveIndex(items.length)}>
                            + Create "${query}"
                        </div>`}
                </div>

                <div class="sw-notes-pane__switcher-hint">
                    ↑↓ navigate · Enter select · Esc close
                </div>
            </div>
        </div>
    `;
}

// Re-export for external use (e.g., saving recents from openNote)
export { _saveRecent as saveRecentNote };
