import { Controller } from 'stimulus';

export default class extends Controller {
    connect() {
    }

    cancelForm() {
        const mainSearchInput = document.querySelector('[data-controller="searchNameInput"]');
        if (mainSearchInput) {
            mainSearchInput.value = '';
        }
        
        const showContent = document.querySelector('.show-content');
        if (showContent) {
            showContent.classList.add('d-none');
            showContent.innerHTML = '';
        }        
    }

    searchForm() {
        // Вызываем глобальную функцию из searchNameInput контроллера
        if (typeof window.performSearch === 'function') {
            window.performSearch();
        } else {
            // Fallback: делаем редирект вручную
            const input = document.querySelector('[data-controller="searchNameInput"]');
            const selectSearch = document.getElementById("select-search").value;
            const searchValue = input ? input.value.trim() : '';
            
            if (searchValue) {
                const encodedValue = encodeURIComponent(searchValue);
                // Извлекаем alias из текущего URL, если он есть
                const currentPath = window.location.pathname;
                const aliasMatch = currentPath.match(/\/specialists\/([^\/]+)/);
                const alias = aliasMatch ? aliasMatch[1] : null;
                
                let url;
                
                if (selectSearch === 'name') {
                    const baseUrl = alias ? `/specialists/${alias}` : '/specialists';
                    url = `${baseUrl}?specialist_search%5Bname%5D=${encodedValue}`;
                } else if (selectSearch === 'pl') {
                    url = `/stoimost-uslug?price_list_form%5Bschname%5D=${encodedValue}`;
                } else if (selectSearch === 'department') {
                    const baseUrl = alias ? `/specialists/${alias}` : '/specialists';
                    url = `${baseUrl}?specialist_search%5Bdepartment%5D=${encodedValue}`;
                }
                
                if (url) {
                    window.location.href = url;
                }
            }
        }
        
        console.log('searchForm вызван');
    }
}