import { Controller } from "@hotwired/stimulus";
import Mousetrap from "mousetrap";
import "@tailwindplus/elements";

export default class extends Controller {
    static targets = ["dialog", "list", "listContainer", "frame", "layoutWrapper", "palette", "searchHeader", "panel"];

    connect() {
        Mousetrap.bind(['mod+enter'], (e) => {
            e.preventDefault();
            this.open();
        });

        const onReady = () => {
                this.paletteTarget.setFilterCallback(({ query, node, content }) => {
                    if (!query) return true;
                    console.log(query, node, content);
                    return content.toLowerCase().includes(query.toLowerCase())
                });
        };

        if (customElements.get('el-command-palette')) {
            onReady();
        } else {
            window.addEventListener('elements:ready', onReady);
        }

        if (this.hasDialogTarget) {
            this.dialogTarget.addEventListener('close', () => this.reset());
        }

        if (this.hasFrameTarget) {
            this.observer = new MutationObserver(() => {
                const hasContent = this.frameTarget.innerHTML.trim().length > 0;
                if (hasContent) {
                    if (this.hasListContainerTarget) this.listContainerTarget.hidden = true;
                    this.frameTarget.classList.remove('hidden');
                    requestAnimationFrame(() => {
                        this.frameTarget.dataset.hasContent = 'true';
                        if (this.hasPanelTarget) this.panelTarget.dataset.hasContent = 'true';
                    });
                } else {
                    if (this.hasListContainerTarget) this.listContainerTarget.hidden = false;
                    this.frameTarget.classList.add('hidden');
                    this.frameTarget.dataset.hasContent = 'false';
                    if (this.hasPanelTarget) this.panelTarget.dataset.hasContent = 'false';
                }
            });
            this.observer.observe(this.frameTarget, {
                childList: true,
                characterData: true,
                subtree: true,
            });
        }
    }

    disconnect() {
        if (this.observer) {
            this.observer.disconnect();
        }
        Mousetrap.unbind(['mod+enter']);
    }

    open(event) {
        if (event) event.preventDefault();
        
        const dialog = this.dialogTarget;
        if (dialog.showModal) {
            dialog.showModal();
        } else {
            dialog.setAttribute('open', '');
        }
        this.reset();
    }

    onSelect(event) {
        const item = event.detail?.relatedTarget || event.target.closest('a');
        if (!item) return;

        if (item.href && !item.href.endsWith('#') && !item.hasAttribute('data-turbo-stream')) {
            window.location.href = item.href;
            return;
        }

        if (item.hasAttribute('data-turbo-stream')) {
            item.click();
        }
    }

    reset() {
        if (this.hasLayoutWrapperTarget) this.layoutWrapperTarget.hidden = false;
        if (this.hasSearchHeaderTarget) this.searchHeaderTarget.hidden = false;
        if (this.hasFrameTarget) this.frameTarget.innerHTML = '';
    }
}
