let originalTree = [];
let categoryMap = {};
const dropdownContent = document.querySelector('.categories-dropdown-content');
const searchInput = document.querySelector('.search-input');
const categoriesList = document.querySelector('.categories-list');

let holdertext = localStorage.getItem('holdertext');
let selectedCategoryId = localStorage.getItem('selectedCategoryId') || null;
let selectedCategoryName = localStorage.getItem('selectedCategoryName') || holdertext;

document.querySelector('.selected-display').textContent = selectedCategoryName;

// Fetch categories from PHP endpoint
function loadCategories() {
	dropdownContent.classList.add('loading');
	
	fetch('index.php?option=com_edocman&task=listcategoriesjson&tmpl=component&format=raw')
		.then(response => {
			if (!response.ok) throw new Error('Network response was not ok');
			return response.json();
		})
		.then(processCategories)
		.then(initDropdown)
		.catch(error => {
			console.error('Error:', error);
			dropdownContent.classList.remove('loading');
		});
}

// Process categories data
function processCategories(categories) {
	categoryMap = {};
	categories.forEach(cat => {
		categoryMap[cat.id] = cat;
		let trail = [];
		let currentId = cat.parent_id;
		while (currentId !== 0 && categoryMap[currentId]) {
			trail.unshift(categoryMap[currentId].name);
			currentId = categoryMap[currentId].parent_id;
		}
		cat.parentTrail = trail.join(' > ');
	});
	
	originalTree = buildTree(categories);
	return originalTree;
}

// Build hierarchical tree structure
function buildTree(categories, parentId = 0) {
	return categories
		.filter(cat => cat.parent_id === parentId)
		.map(cat => ({
			...cat,
			children: buildTree(categories, cat.id)
		}));
}

function updateSelection(category) {
	selectedCategoryId = category.id;
	selectedCategoryName = category.name;
	localStorage.setItem('selectedCategoryId', category.id);
	localStorage.setItem('selectedCategoryName', category.name);
	document.querySelector('.selected-display').textContent = category.name;
}

// Render categories list
function renderCategories(tree, isSearchMode = false) {
	return tree.map(node => `
		<div class="category-item ${selectedCategoryId == node.id ? 'selected-category' : ''}" data-id="${node.id}">
			${node.children.length ? 
				`<span class="toggle-btn ${isSearchMode ? 'expanded' : 'collapsed'}"></span>` : 
				'<span class="toggle-btn"></span>'}
			<span class="category-name">${node.name}</span>
			${node.parentTrail ? `<span class="parent-trail">${node.parentTrail}</span>` : ''}
		</div>
		${node.children.length ? `
			<div class="children" style="display: ${isSearchMode ? 'block' : 'none'}">
				${renderCategories(node.children, isSearchMode)}
			</div>
		` : ''}
	`).join('');
}

// Filter categories tree
function filterTree(tree, searchTerm) {
	if (!searchTerm) return tree;
	return tree
		.map(node => {
			const children = filterTree(node.children, searchTerm);
			const matches = node.name.toLowerCase().includes(searchTerm.toLowerCase());
			return matches || children.length ? { ...node, children } : null;
		})
		.filter(Boolean);
}

// Initialize dropdown
function initDropdown() {
	categoriesList.innerHTML = renderCategories(originalTree);
	dropdownContent.classList.remove('loading');
	
	// Event listeners
	document.querySelector('.selected-display').addEventListener('click', toggleDropdown);
	categoriesList.addEventListener('click', handleListClick);
	searchInput.addEventListener('input', handleSearch);
	document.addEventListener('click', handleOutsideClick);
}

// Event handlers
function toggleDropdown() {
	const isOpen = dropdownContent.style.display === 'block';
	dropdownContent.style.display = isOpen ? 'none' : 'block';
	searchInput.style.display = isOpen ? 'none' : 'block';
	if (!isOpen) searchInput.focus();
}

function handleListClick(e) {
	const toggleBtn = e.target.closest('.toggle-btn');
	if (toggleBtn) {
		const childrenDiv = toggleBtn.parentElement.nextElementSibling;
		if (childrenDiv?.classList.contains('children')) {
			const isCollapsed = childrenDiv.style.display === 'none';
			childrenDiv.style.display = isCollapsed ? 'block' : 'none';
			toggleBtn.classList.toggle('collapsed');
			toggleBtn.classList.toggle('expanded');
		}
		return;
	}

	const categoryItem = e.target.closest('.category-item');
	if (categoryItem) {

		//document.querySelector('.selected-display').textContent =  categoryItem.querySelector('.category-name').textContent;
		dropdownContent.style.display = 'none';

		const category = categoryMap[categoryItem.dataset.id];
		selectedCategoryId = category.id;
		selectedCategoryName = category.name;
		localStorage.setItem('selectedCategoryId', category.id);
		localStorage.setItem('selectedCategoryName', category.name);
		
		document.getElementById('jformcategory_id').value = selectedCategoryId;

		document.querySelector('.selected-display').textContent = category.name;

		document.querySelectorAll('.category-item').forEach(item => {
			item.classList.remove('selected-category');
		});
		categoryItem.classList.add('selected-category');
		updateClearButton();
	}
}

function handleSearch(e) {
	const filteredTree = filterTree(originalTree, e.target.value);
	categoriesList.innerHTML = renderCategories(filteredTree, e.target.value.length > 0);
}

function handleOutsideClick(e) {
	if (!e.target.closest('.categories-dropdown')) {
		dropdownContent.style.display = 'none';
		searchInput.style.display = 'none';
	}
}

function clearSelection() {
	localStorage.removeItem('selectedCategoryId');
	localStorage.removeItem('selectedCategoryName');
	selectedCategoryId = null;
	selectedCategoryName = holdertext;
	document.querySelector('.selected-display').textContent = selectedCategoryName;
	document.querySelectorAll('.selected-category').forEach(item => {
		item.classList.remove('selected-category');
	});
}

function updateClearButton() {
	const clearBtn = document.querySelector('.categories-dropdown-clear-btn');
	clearBtn.style.display = selectedCategoryId ? 'block' : 'none';
}


 function clearSelection() {
	selectedCategoryId = null;
	selectedCategoryName = holdertext;
	localStorage.removeItem('selectedCategoryId');
	localStorage.removeItem('selectedCategoryName');
	document.querySelector('.selected-display').textContent = selectedCategoryName;
	document.querySelectorAll('.category-item').forEach(item => {
		item.classList.remove('selected');
	});
	updateClearButton();
}

function handleClearClick(e) {
	e.preventDefault(); 
	e.stopPropagation(); 
	clearSelection();
}

// Thêm sự kiện cho nút clear
document.querySelector('.categories-dropdown-clear-btn').addEventListener('click', handleClearClick);

// Start application
loadCategories();
updateClearButton();