// ==========================================
// NotesPane Kit — NoteList
// ==========================================
// List view: toolbar, search, filters, tag cloud,
// scrollable note list with pinned section,
// selection bar, and pagination.
// Independently importable.

import { NoteListItem } from './note-list-item.js';

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

/**
 * @param {{
 *   notes: Array, loading: boolean, hasMore: boolean, loadMore: () => void,
 *   folders: Array, folder: string, setFolder: (f: string) => void,
 *   sort: string, setSort: (s: string) => void,
 *   searchQuery: string, setSearchQuery: (q: string) => void,
 *   tagFilter: string, setTagFilter: (t: string) => void,
 *   selectMode: boolean, selectedIds: Set, enterSelectMode: () => void,
 *   exitSelectMode: () => void, toggleSelect: (id: string) => void,
 *   toggleSelectAll: (checked: boolean) => void, bulkDelete: () => void,
 *   onNoteClick: (id: string) => void, onNewNote: () => void,
 *   onDailyNote: () => void, onGraphClick: () => void,
 *   pinnedIds: Set, togglePin: (id: string) => void,
 * }} props
 */
export function NoteList(props) {
    const {
        notes, loading, hasMore, loadMore,
        folders, folder, setFolder,
        sort, setSort,
        searchQuery, setSearchQuery,
        tagFilter, setTagFilter,
        selectMode, selectedIds, enterSelectMode, exitSelectMode,
        toggleSelect, toggleSelectAll, bulkDelete,
        onNoteClick, onNewNote, onDailyNote, onGraphClick,
        pinnedIds, togglePin,
        standalone = true,
    } = props;

    // When standalone=false, the surface sidebar owns search/filter/tag controls
    const showFilters = standalone !== false;

    const searchTimerRef = useRef(null);
    const searchInputRef = useRef(null);

    const onSearchInput = useCallback((e) => {
        const val = e.target.value;
        clearTimeout(searchTimerRef.current);
        searchTimerRef.current = setTimeout(() => {
            if (val.trim().length >= 2 || val.trim().length === 0) {
                setSearchQuery(val.trim());
            }
        }, 300);
    }, [setSearchQuery]);

    // ── Tag cloud: collect tags from visible notes ──
    const tagCounts = {};
    for (const n of notes) {
        for (const t of (n.tags || [])) {
            tagCounts[t] = (tagCounts[t] || 0) + 1;
        }
    }
    const topTags = Object.entries(tagCounts)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 15);

    // ── Split pinned vs unpinned ──
    const isSearch = searchQuery && searchQuery.length >= 2;
    const pinnedNotes = isSearch ? [] : notes.filter(n => pinnedIds.has(n.id));
    const unpinnedNotes = isSearch ? notes : notes.filter(n => !pinnedIds.has(n.id));

    return html`
        <div class="sw-notes-pane__toolbar">
            <button class="sw-notes-pane__toolbar-btn" onClick=${onNewNote} title="New note">+ New</button>
            <button class="sw-notes-pane__toolbar-btn" onClick=${onDailyNote} title="Daily note">Today</button>
            ${onGraphClick && html`
                <button class="sw-notes-pane__toolbar-btn" onClick=${onGraphClick} title="Graph view">Graph</button>`}
            <span class="sw-notes-pane__toolbar-spacer" />
            <button class="sw-notes-pane__toolbar-btn" onClick=${() => selectMode ? exitSelectMode() : enterSelectMode()}
                    title=${selectMode ? 'Cancel selection' : 'Select mode'}>
                ${selectMode ? 'Cancel' : 'Select'}
            </button>
        </div>

        ${showFilters && html`
            <div class="sw-notes-pane__search-row">
                <input class="sw-notes-pane__search-input" type="text"
                       placeholder="Search notes\u2026" autocomplete="off"
                       ref=${searchInputRef} onInput=${onSearchInput}
                       value=${searchQuery} />
            </div>`}

        ${showFilters && html`
            <div class="sw-notes-pane__filter-row">
                <select class="sw-notes-pane__filter-select"
                        value=${folder} onChange=${e => { setFolder(e.target.value); }}>
                    <option value="">All folders</option>
                    ${folders.map(f => html`
                        <option key=${f.path} value=${f.path}>${f.path} (${f.count})</option>`)}
                </select>
                <select class="sw-notes-pane__filter-select"
                        value=${sort} onChange=${e => setSort(e.target.value)}>
                    <option value="updated_desc">Last updated</option>
                    <option value="created_desc">Created</option>
                    <option value="alpha">Alphabetical</option>
                </select>
            </div>`}

        ${showFilters && topTags.length > 0 && html`
            <div class="sw-notes-pane__tag-cloud">
                ${topTags.map(([tag, count]) => html`
                    <span key=${tag}
                          class=${'sw-notes-pane__tag-chip' + (tagFilter === tag ? ' sw-notes-pane__tag-chip--active' : '')}
                          onClick=${() => setTagFilter(tagFilter === tag ? '' : tag)}>
                        ${tag}
                    </span>`)}
            </div>`}

        <div class="sw-notes-pane__list">
            ${loading && notes.length === 0 && html`
                <div class="sw-notes-pane__loading">Loading\u2026</div>`}

            ${!loading && notes.length === 0 && html`
                <div class="sw-notes-pane__list-empty">
                    ${isSearch ? 'No results found' : (folder ? 'No notes in this folder' : 'No notes yet. Create one!')}
                </div>`}

            ${pinnedNotes.length > 0 && html`
                <div class="sw-notes-pane__pinned-divider">Pinned</div>
                ${pinnedNotes.map(n => html`
                    <${NoteListItem} key=${n.id} note=${n} isSearch=${isSearch}
                        onClick=${onNoteClick} selectMode=${selectMode}
                        selected=${selectedIds.has(n.id)} onToggleSelect=${toggleSelect}
                        pinned=${true} onTogglePin=${togglePin} />`)}
                ${unpinnedNotes.length > 0 && html`
                    <div class="sw-notes-pane__pinned-divider">Notes</div>`}`}

            ${unpinnedNotes.map(n => html`
                <${NoteListItem} key=${n.id} note=${n} isSearch=${isSearch}
                    onClick=${onNoteClick} selectMode=${selectMode}
                    selected=${selectedIds.has(n.id)} onToggleSelect=${toggleSelect}
                    pinned=${false} onTogglePin=${togglePin} />`)}

            ${hasMore && html`
                <button class="sw-notes-pane__load-more" onClick=${loadMore}>
                    Load more\u2026
                </button>`}
        </div>

        ${selectMode && html`
            <div class="sw-notes-pane__selection-bar">
                <label>
                    <input type="checkbox"
                           checked=${selectedIds.size === notes.length && notes.length > 0}
                           onChange=${e => toggleSelectAll(e.target.checked)} />
                    All
                </label>
                <span>${selectedIds.size} selected</span>
                <button class="sw-notes-pane__toolbar-btn" onClick=${bulkDelete}
                        style="color:var(--danger);border-color:var(--danger)">
                    Delete
                </button>
                <button class="sw-notes-pane__toolbar-btn" onClick=${exitSelectMode}>Cancel</button>
            </div>`}
    `;
}
