// ==========================================
// NotesPane Kit — NoteEditor
// ==========================================
// Editor view: title, folder, tags, content with
// CM6 integration (falls back to textarea).
// Word/char count, keyboard shortcuts.
// Independently importable.

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

/**
 * @param {{
 *   currentNote: object|null,
 *   editingId: string|null,
 *   folders: Array,
 *   onSave: (fields: object) => Promise<boolean>,
 *   onCancel: () => void,
 *   onDelete: () => void,
 * }} props
 */
export function NoteEditor(props) {
    const { currentNote, editingId, folders, onSave, onCancel, onDelete } = props;

    const [title, setTitle] = useState(currentNote?.title || '');
    const [folderPath, setFolderPath] = useState(currentNote?.folder_path || '');
    const [tags, setTags] = useState((currentNote?.tags || []).join(', '));
    const [content, setContent] = useState(currentNote?.content || '');
    const [saving, setSaving] = useState(false);

    const titleRef = useRef(null);
    const contentRef = useRef(null);
    const cmEditorRef = useRef(null);
    const containerRef = useRef(null);

    // ── Populate from note ──────────────────
    useEffect(() => {
        setTitle(currentNote?.title || '');
        setFolderPath(currentNote?.folder_path || '');
        setTags((currentNote?.tags || []).join(', '));
        setContent(currentNote?.content || '');
        // Destroy old CM editor if any
        if (cmEditorRef.current) {
            cmEditorRef.current.destroy();
            cmEditorRef.current = null;
        }
    }, [currentNote?.id]);

    // ── Auto-focus title on new note ────────
    useEffect(() => {
        if (!editingId && titleRef.current) {
            titleRef.current.focus();
        }
    }, [editingId]);

    // ── CM6 integration ─────────────────────
    useEffect(() => {
        const cmContainer = containerRef.current;
        if (!cmContainer) return;

        if (window.CM?.noteEditor && !cmEditorRef.current) {
            cmContainer.innerHTML = '';
            cmEditorRef.current = window.CM.noteEditor(cmContainer, {
                value: content,
                darkMode: document.documentElement.getAttribute('data-theme') !== 'light',
                onChange: (val) => setContent(val),
                onLink: null, // handled by reader, not editor
                linkCompleter: async (query) => {
                    if (!query || query.length < 1) return [];
                    try {
                        const resp = await window.sw.api.notes.searchTitles(query, 8);
                        return (resp || []).map(n => ({ label: n.title, id: n.id }));
                    } catch { return []; }
                },
            });
        }

        return () => {
            if (cmEditorRef.current) {
                cmEditorRef.current.destroy();
                cmEditorRef.current = null;
            }
        };
    }, []);

    // ── Get content (CM or textarea) ────────
    const getContent = useCallback(() => {
        if (cmEditorRef.current) return cmEditorRef.current.getValue();
        return content;
    }, [content]);

    // ── Word/char count ─────────────────────
    const wordCount = content ? content.trim().split(/\s+/).filter(Boolean).length : 0;
    const charCount = content ? content.length : 0;

    // ── Save handler ────────────────────────
    const handleSave = useCallback(async () => {
        if (saving) return;
        setSaving(true);
        const tagsArr = tags ? tags.split(',').map(t => t.trim()).filter(Boolean) : [];
        const ok = await onSave({
            title: title.trim(),
            content: getContent(),
            folder_path: folderPath.trim(),
            tags: tagsArr,
        });
        setSaving(false);
    }, [title, folderPath, tags, getContent, onSave, saving]);

    // ── Keyboard shortcuts ──────────────────
    useEffect(() => {
        const handler = (e) => {
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault();
                handleSave();
            }
            if (e.key === 'Escape') {
                e.preventDefault();
                onCancel();
            }
        };
        document.addEventListener('keydown', handler);
        return () => document.removeEventListener('keydown', handler);
    }, [handleSave, onCancel]);

    return html`
        <div class="sw-notes-pane__editor-header">
            <button class="sw-notes-pane__toolbar-btn" onClick=${onCancel}>← Back</button>
            <span class="sw-notes-pane__editor-header-spacer" />
            ${editingId && html`
                <button class="sw-notes-pane__toolbar-btn"
                        style="color:var(--danger);border-color:var(--danger)"
                        onClick=${onDelete}>Delete</button>`}
            <button class="sw-notes-pane__toolbar-btn"
                    style="color:var(--success);border-color:var(--success)"
                    onClick=${handleSave} disabled=${saving}>
                ${saving ? 'Saving\u2026' : 'Save'}
            </button>
        </div>

        <div class="sw-notes-pane__editor">
            <input class="sw-notes-pane__editor-title" type="text"
                   ref=${titleRef} placeholder="Note title"
                   value=${title} onInput=${e => setTitle(e.target.value)} />

            <div class="sw-notes-pane__editor-meta">
                <input type="text" placeholder="Folder (e.g. /work/project)"
                       value=${folderPath} onInput=${e => setFolderPath(e.target.value)}
                       list="sw-notes-folders" />
                <datalist id="sw-notes-folders">
                    ${folders.map(f => html`<option key=${f.path} value=${f.path} />`)}
                </datalist>
                <input type="text" placeholder="Tags (comma-separated)"
                       value=${tags} onInput=${e => setTags(e.target.value)} />
            </div>

            <div class="sw-notes-pane__editor-content" ref=${containerRef}>
                ${!window.CM?.noteEditor && html`
                    <textarea class="sw-notes-pane__editor-textarea"
                              ref=${contentRef}
                              placeholder="Write your note in markdown\u2026"
                              value=${content}
                              onInput=${e => setContent(e.target.value)} />`}
            </div>

            <div class="sw-notes-pane__editor-footer">
                <span>${wordCount} words · ${charCount} chars</span>
                <span style="color:var(--text-3)">Ctrl+S to save · Esc to cancel</span>
            </div>
        </div>
    `;
}
