var LOCAL_STORAGE_ADD_PANEL_ORDER_KEY = 'wmd_add_panel_order';
var LOCAL_STORAGE_KEY                 = 'wmd_add_domain_columns';
var LOCAL_STORAGE_CAT                 = 'wmd_add_domain_last_category';
var LOCAL_STORAGE_FILTER_MODE         = 'wmd_add_domain_filter_mode';
var FIXED_SELECTED_COLUMNS 			  = null;
var columnFilterMode 				  = 'custom_notes';
var columnsMeta 					  = {};

///////////////////////////////////////////////////////////////////////////////

try {
	var storedFilter = localStorage.getItem(LOCAL_STORAGE_FILTER_MODE);
	if (storedFilter) {
		columnFilterMode = storedFilter;
	}
} catch (e) {}

///////////////////////////////////////////////////////////////////////////////

document.addEventListener("DOMContentLoaded", async function() {
	await initApp();
	showBody();
});

///////////////////////////////////////////////////////////////////////////////

async function initApp() {
	var loggedIn = await checkAuthSession();
    if (!loggedIn) return;
	startAuthSessionMonitor();
	initEventButtons();
	initSingleDomainAdd();
	initBulkDomainAdd();
	
	if (!IS_ADMIN) {
		var panel = document.querySelector('.field-selection-panel');
		if (panel) {
			panel.style.display = 'none';
		}
	}

	loadCategories();
	await loadConfigJson();  // ALWAYS load config if it exists

	initDefaultSelections();

	loadColumns();
	setupClearButton();
	setupAddModeOrderSwitcher();
	applyAddModeOrder();
	if (IS_ADMIN) {
		setupAdminConfigExport();
	}
}

///////////////////////////////////////////////////////////////////////////////

function initSingleDomainAdd() {
	document.getElementById("add-domain-form").addEventListener("submit", async function (e) {
		if (!USE_JS_ADD_HANDLER) return; 

		e.preventDefault(); // JS will handle submission

		showSubmitStatus("Adding Domains");
		
		const domain = document.getElementById("domain").value.trim();
		const categoryId = document.getElementById("category_id").value;

		const cols = getSelectedColumns();
		const headers = ["domain"].concat(cols);

		const row = [domain];

		cols.forEach(col => {
			const v = document.getElementById("col_" + col)?.value || "";
			row.push(v);
		});

		const csv = headers.join(",") + "\n" + row.join(",");

		const result = await sendCsvToAddApi_JS(csv, categoryId);

		if (result.status === "ok") {
			if(result.added)
				showSubmitStatus("One Domain added successfully");
			else
				showSubmitStatus("Zero Domains added successfully. The domain was likely already in the portfolio.");
		} else {
			showSubmitStatus("Error adding domain:\n" + (result.error || JSON.stringify(result, null, 2)));
			console.error(result);
		}
	});
}

///////////////////////////////////////////////////////////////////////////////

function initBulkDomainAdd() {
	document.getElementById("bulk-add-form").addEventListener("submit", async function (e) {

		if (!USE_JS_ADD_HANDLER) return;

		e.preventDefault();
		
		showSubmitStatus("Adding domains");

		const text = document.getElementById("bulk_csv").value.trim();
		const categoryId = document.getElementById("bulk_category_id").value;

		if (!text) {
			showSubmitStatus("CSV cannot be empty");
			return;
		}

		const cols = getSelectedColumns();
		const headers = ["domain"].concat(cols);

		let csv = headers.join(",") + "\n";

		const lines = text.split("\n");

		lines.forEach(line => {
			const trimmed = line.trim();
			if (!trimmed) return;

			const parts = trimmed.split(",");
			while (parts.length < headers.length) {
				parts.push("");
			}

			csv += parts.join(",") + "\n";
		});

		const result = await sendCsvToAddApi_JS(csv, categoryId);

		if (result.status === "ok") {
			showSubmitStatus(result.added + " domains added successfully.");
		} else {
			showSubmitStatus("Error adding domains:\n" + (result.error || JSON.stringify(result, null, 2)));
			console.error(result);
		}
	});
}

///////////////////////////////////////////////////////////////////////////////

function initDefaultSelections() {
	var filterModeSelect = document.getElementById('column_filter_mode');
    if (filterModeSelect && IS_ADMIN) {
        filterModeSelect.value = columnFilterMode;
		filterModeSelect.addEventListener('change', function () {
            columnFilterMode = this.value;
            try {
                localStorage.setItem(LOCAL_STORAGE_FILTER_MODE, columnFilterMode);
            } catch (e) {}
            loadColumns(); // reload with new mode
        });
    }

    document.getElementById('category_id').addEventListener('change', function () {
        try {
            localStorage.setItem(LOCAL_STORAGE_CAT, this.value);
        } catch (e) {}
    });
	
	document.getElementById('bulk_category_id').addEventListener('change', function () {
        try {
            localStorage.setItem(LOCAL_STORAGE_CAT, this.value);
        } catch (e) {}
    });
}

///////////////////////////////////////////////////////////////////////////////

function applyAddModeOrder() {
	var mode = localStorage.getItem(LOCAL_STORAGE_ADD_PANEL_ORDER_KEY) || 'single';
	
	//if(mode == "bulk")
	//	 document.getElementById("domain_add_mode").checked = true;

	var select = document.getElementById('add_mode');
	if (select) select.value = mode;

	var panel = document.querySelector('.add-domain-panel');
	if (!panel) return;

	var single = document.getElementById('single-add-container');
	var bulk   = document.getElementById('bulk-add-container');

	if (mode === 'bulk') {
		bulk.style.display = 'block';
		single.style.display = 'none';
		// auto-focus domain input
		var domainInput = document.getElementById('bulk_csv');
		if (domainInput) {
			domainInput.focus();
		}
	} else {
		single.style.display = 'block';
		bulk.style.display = 'none';
		var domainInput = document.getElementById('domain');
		if (domainInput) {
			domainInput.focus();
		}
	}
}

///////////////////////////////////////////////////////////////////////////////

function getSelectedColumns() {
	// Non-admin → use server-defined order
	if (!IS_ADMIN && Array.isArray(FIXED_SELECTED_COLUMNS)) {
		return FIXED_SELECTED_COLUMNS.slice();
	}

	// Admin → always use localStorage-defined order
	var s = localStorage.getItem(LOCAL_STORAGE_KEY);
	if (s) {
		try {
			var arr = JSON.parse(s);
			if (Array.isArray(arr)) return arr.slice();
		} catch (e) {}
	}

	return [];
}

///////////////////////////////////////////////////////////////////////////////

function showSubmitStatus(statusText) {
	var mode = localStorage.getItem(LOCAL_STORAGE_ADD_PANEL_ORDER_KEY) || 'single';
	if(mode === "bulk") {
		var elem = document.getElementById('bulk-domain-add-status');
	}
	else {
		var elem = document.getElementById('single-domain-add-status');
	}
	elem.innerHTML = statusText;
}

///////////////////////////////////////////////////////////////////////////////

function loadCategories() {
	var url = API_BASE_URL + '?c=list&t=category&oper=user';

	fetch(url, { credentials: 'same-origin' })
		.then(function(res) { return res.json(); })
		.then(function(data) {
			var singleSelect = document.getElementById('category_id');
			var bulkSelect   = document.getElementById('bulk_category_id');

			if (!data || !Array.isArray(data.ids)) {
				return;
			}

			/* ---------------------------------------------------------
			 * Restore previously selected/saved category for SINGLE ADD
			 * --------------------------------------------------------- */
			var savedCat = null;
			// last category saved in localStorage
			try {
				savedCat = localStorage.getItem(LOCAL_STORAGE_CAT);
			} catch (e) {
				savedCat = null;
			}

			/* ---------------------------------------------------------
			 * Populate both dropdowns
			 * --------------------------------------------------------- */

			data.ids.forEach(function(cat) {

				/* ---- Single-add dropdown ---- */
				if (singleSelect) {
					var opt1 = document.createElement('option');
					opt1.value = cat.id;
					opt1.textContent = cat.name;

					if (savedCat !== null && savedCat === String(cat.id)) {
						opt1.selected = true;
					}

					singleSelect.appendChild(opt1);
				}

				/* ---- Bulk-add dropdown ---- */
				if (bulkSelect) {
					var opt2 = document.createElement('option');
					opt2.value = cat.id;
					opt2.textContent = cat.name;
					
					if (savedCat !== null && savedCat === String(cat.id)) {
						opt2.selected = true;
					}

					// Bulk dropdown does NOT auto-select anything.
					bulkSelect.appendChild(opt2);
				}

			});
		})
		.catch(function() {
			// Ignore errors — dropdowns will just show "No category"
		});
}

///////////////////////////////////////////////////////////////////////////////

function setupAddModeOrderSwitcher() {
	
	var select = document.getElementById('add_mode');
	if (!select) return;

	select.addEventListener('change', function () {
		localStorage.setItem(LOCAL_STORAGE_ADD_PANEL_ORDER_KEY, this.value);
		applyAddModeOrder();
	});
	
	/*
	const cb = document.getElementById("domain_add_mode");
	cb.addEventListener("change", () => {
		value = cb.checked ? "bulk" : "single"
		localStorage.setItem(LOCAL_STORAGE_ADD_PANEL_ORDER_KEY, value);
		applyAddModeOrder();
	});
	*/
}
	
///////////////////////////////////////////////////////////////////////////////
    
function updateBulkHelpText() {
	var help = document.getElementById('bulk-help-text');
	if (!help) return;

	var selected = getSelectedColumns();

	// Build ordered label list: domain + selected column names
	var cols = ['domain'].concat(selected);

	help.innerHTML =
		'<span>' + cols.join('</span> <span>') + '</span>';
}

///////////////////////////////////////////////////////////////////////////////

function updateBulkPlaceholder() {
	var bulkTA = document.getElementById('bulk_csv');
	if (!bulkTA) return;

	var selected = getSelectedColumns();
	var cols = ['example.com'].concat(selected.map(function () { return 'value'; }));

	var row1 = cols.join(', ');
	var row2 = row1.replace('example.com', 'example.net');

	bulkTA.placeholder = row1 + "\n" + row2;
}

///////////////////////////////////////////////////////////////////////////////

async function loadConfigJson() {
	try {
		const raw = await get_config_data(ADD_DOMAINS_CONFIG_KEY, API_BASE_URL);
		if (!raw) return;

		const cfg = JSON.parse(raw);

		if (cfg.selected_columns) {
			FIXED_SELECTED_COLUMNS = cfg.selected_columns.slice();
		}
		if (cfg.filter_mode) {
			columnFilterMode = cfg.filter_mode;
			try {
				localStorage.setItem(LOCAL_STORAGE_FILTER_MODE, columnFilterMode);
			} catch (e) {}
		}
	} catch (e) {
		// No config available yet; silently ignore
	}
}

///////////////////////////////////////////////////////////////////////////////

function isNotesColumn(name) {
	return /^notes_[a-d]$/i.test(name);
}

///////////////////////////////////////////////////////////////////////////////

function autoLabel(name) {
	if (!name) return '';
	return name
		.replace(/_/g, ' ')
		.replace(/\s+/g, ' ')
		.trim()
		.replace(/\b\w/g, function (c) { return c.toUpperCase(); });
}

///////////////////////////////////////////////////////////////////////////////

function updateHintVisibility() {
	var hint = document.getElementById('column-hint');
	if (!hint) return;

	if (columnFilterMode === 'all') {
		hint.style.display = 'block';
	} else {
		hint.style.display = 'none';
	}
}

///////////////////////////////////////////////////////////////////////////////

function saveDraggedOrder() {
	var container = document.getElementById("columns-list");
	var items = container.querySelectorAll(".columns-list-item");

	var newOrder = [];

	items.forEach(function (item) {
		var checkbox = item.querySelector("input[type='checkbox']");
		if (checkbox && checkbox.checked) {
			newOrder.push(checkbox.value);
		}
	});

	localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(newOrder));

	updateExtraColumnsHiddenField();
	rebuildExtraFields();
	updateBulkHelpText();
	updateBulkPlaceholder();
}

///////////////////////////////////////////////////////////////////////////////

function enableDragAndDrop() {
	var container = document.getElementById("columns-list");

	var items = container.querySelectorAll(".columns-list-item");

	items.forEach(function (item) {
		var checkbox = item.querySelector("input[type='checkbox']");

		// Only selected items are draggable
		if (checkbox && checkbox.checked) {
			item.setAttribute("draggable", "true");
		} else {
			item.removeAttribute("draggable");
		}

		item.addEventListener("dragstart", function (e) {
			if (!checkbox.checked) {
				e.preventDefault();
				return;
			}
			e.dataTransfer.setData("text/plain", item.dataset.colName = checkbox.value);
			item.classList.add("dragging");
		});

		item.addEventListener("dragend", function () {
			item.classList.remove("dragging");
		});

		item.addEventListener("dragover", function (e) {
			e.preventDefault();
			var dragging = container.querySelector(".dragging");
			if (!dragging) return;

			// Only reorder among selected items
			var overCheckbox = item.querySelector("input[type='checkbox']");
			if (!overCheckbox.checked) return;

			var bounding = item.getBoundingClientRect();
			var offset = e.clientY - bounding.top;

			if (offset > bounding.height / 2) {
				container.insertBefore(dragging, item.nextSibling);
			} else {
				container.insertBefore(dragging, item);
			}
		});

	});

	// Save order after any drop
	container.addEventListener("drop", function () {
		saveDraggedOrder();
	});
}

///////////////////////////////////////////////////////////////////////////////

function loadColumns() {
	var url = API_BASE_URL + '?c=list&t=domain&oper=columns';

	fetch(url, {credentials: 'same-origin'})
		.then(function (res) { return res.json(); })
		.then(function (data) {
			var container = document.getElementById('columns-list');
			if (!container) return;

			if (!data || !data.columns) {
				container.textContent = 'Could not load columns from API.';
				return;
			}

			columnsMeta = data.columns;

			if (!IS_ADMIN) {
				// Non-admin (or admin in regular-user view): do not allow changing columns; just use config JSON.
				container.innerHTML = '<div class="columns-list-note">Field configuration has been set by the administrator.</div>';
				updateExtraColumnsHiddenField();
				rebuildExtraFields();
				updateHintVisibility();
				updateBulkHelpText();
				updateBulkPlaceholder();
				return;
			}

			container.innerHTML = '';

			var savedSelection = [];
			try {
				var stored = localStorage.getItem(LOCAL_STORAGE_KEY);
				if (stored) {
					savedSelection = JSON.parse(stored);
					if (!Array.isArray(savedSelection)) {
						savedSelection = [];
					}
				}
			} catch (e) {
				savedSelection = [];
			}

			var selectedNames = new Set(savedSelection);

			// Build ordered lists
			var selectedList = savedSelection.slice(); // preserve order exactly
			var customList = [];
			var otherList = [];

			// Classify remaining columns
			Object.keys(data.columns).forEach(function (colName) {
				var col = data.columns[colName];

				// Must be editable
				if (
					!col ||
					!(
						col.editable == 1 ||
						col.editable === true
					)
				) return;

				// Must be visible in gridview
				if (!(col.gridview == 1 || col.gridview === true)) return;

				// Hard exclusions
				if (EXCLUDED_COLUMNS.indexOf(colName) !== -1) return;

				// Config filter
				if (columnFilterMode === "custom_notes") {
					if (
						!selectedNames.has(colName) &&
						!(col.custom == 1) &&
						!isNotesColumn(colName)
					) return;
				}

				// Already selected — skip, already in selectedList
				if (selectedNames.has(colName)) return;

				// Custom fields after selected
				if (col.custom == 1) {
					customList.push(colName);
					return;
				}

				// Everything else
				otherList.push(colName);
			});

			// FINAL order: selected → custom → everything else
			var ordered = selectedList.concat(customList).concat(otherList);


			// Render in the new order
			ordered.forEach(function (colName) {
				var col = data.columns[colName];

				var item = document.createElement('div');
				item.className = 'columns-list-item';

				var checkbox = document.createElement('input');
				checkbox.type = 'checkbox';
				checkbox.value = colName;
				checkbox.checked = selectedNames.has(colName);

				var displayLabel = col.label && col.label.trim() !== ''
					? col.label
					: autoLabel(colName);

				var labelMain = document.createElement('span');
				labelMain.className = 'columns-list-label-main';
				labelMain.textContent = displayLabel;


				var labelKey = document.createElement('span');
				labelKey.className = 'columns-list-label-key';
				labelKey.textContent = '(' + colName + ')';

				var labelsWrapper = document.createElement('div');
				labelsWrapper.className = 'columns-list-labels';

				labelsWrapper.appendChild(labelMain);
				labelsWrapper.appendChild(labelKey);

				item.appendChild(checkbox);
				item.appendChild(labelsWrapper);

				container.appendChild(item);

				checkbox.addEventListener('change', onColumnSelectionChanged);
			});
			
			if (IS_ADMIN) {
				enableDragAndDrop();
			}

			updateExtraColumnsHiddenField();
			rebuildExtraFields();
			updateHintVisibility();
			updateBulkHelpText();
			updateBulkPlaceholder();
		})
		.catch(function () {
			var container = document.getElementById('columns-list');
			if (container) {
				container.textContent = 'Error loading columns from API.';
			}
		});
}

///////////////////////////////////////////////////////////////////////////////

function onColumnSelectionChanged() {
	if (!IS_ADMIN) {
		return;
	}
	
	var container = document.getElementById("columns-list");
	var items = container.querySelectorAll(".columns-list-item");

	var newOrder = [];
	items.forEach(function (item) {
		var checkbox = item.querySelector("input[type='checkbox']");
		if (checkbox && checkbox.checked) {
			newOrder.push(checkbox.value);
		}
	});
	localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(newOrder));

	updateExtraColumnsHiddenField();
	rebuildExtraFields();
	updateBulkHelpText();
	updateBulkPlaceholder();
}

///////////////////////////////////////////////////////////////////////////////

function updateExtraColumnsHiddenField() {
	var hidden = document.getElementById('extra_columns');
	var bulkHidden = document.getElementById('bulk_extra_columns');
	if (!hidden || !bulkHidden) return;

	var selected = getSelectedColumns();
	hidden.value = selected.join(',');
	bulkHidden.value = selected.join(',');
}

///////////////////////////////////////////////////////////////////////////////

function rebuildExtraFields() {
	var container = document.getElementById('extra-fields-container');
	if (!container) return;

	var selected = getSelectedColumns();
	container.innerHTML = '';

	selected.forEach(function (colName) {
		var meta = columnsMeta[colName] || {};
		var labelText = (meta.label && meta.label.trim() !== '')
			? meta.label
			: autoLabel(colName);
		var fieldType = meta.fieldtype || 'string';

		var row = document.createElement('div');
		row.className = 'field-row';

		var label = document.createElement('label');
		label.htmlFor = 'col_' + colName;

		var labelTitle = document.createElement('span');
		labelTitle.textContent = labelText + ' ';

		var labelKey = document.createElement('span');
		labelKey.style.fontFamily = 'monospace';
		labelKey.style.color = '#555';
		labelKey.textContent = '(' + colName + ')';

		label.appendChild(labelTitle);
		label.appendChild(labelKey);

		var input;

		if (fieldType === 'boolean') {
			input = document.createElement('input');
			input.type = 'checkbox';
			input.value = '1';
		} else if (fieldType === 'integer') {
			input = document.createElement('input');
			input.type = 'number';
		} else if (fieldType === 'date') {
			input = document.createElement('input');
			input.type = 'date';
		} else if (fieldType === 'datetime') {
			input = document.createElement('input');
			input.type = 'datetime-local';
		} else {
			input = document.createElement('input');
			input.type = 'text';
		}

		input.name = 'col_' + colName;
		input.id   = 'col_' + colName;

		if (POSTED_VALUES && POSTED_VALUES.hasOwnProperty('col_' + colName)) {
			var postedVal = POSTED_VALUES['col_' + colName];
			if (input.type === 'checkbox') {
				if (postedVal !== '' && postedVal !== '0') {
					input.checked = true;
				}
			} else {
				input.value = postedVal;
			}
		}

		row.appendChild(label);
		row.appendChild(input);

		container.appendChild(row);
	});
}

///////////////////////////////////////////////////////////////////////////////

function setupClearButton() {
	var clearButton = document.getElementById('clear-form-btn');
	if (!clearButton) return;

	clearButton.addEventListener('click', function () {
		var domainInput = document.getElementById('domain');
		if (domainInput) {
			domainInput.value = '';
		}

		var extraContainer = document.getElementById('extra-fields-container');
		if (extraContainer) {
			var inputs = extraContainer.querySelectorAll('input');
			inputs.forEach(function (input) {
				if (input.type === 'checkbox') {
					input.checked = false;
				} else {
					input.value = '';
				}
			});
		}
	});
}

///////////////////////////////////////////////////////////////////////////////

function setupAdminConfigExport() {
	if (!IS_ADMIN) return;

	var btn = document.getElementById('export-config-btn');
	if (!btn) return;

	btn.addEventListener('click', async function () {

		// 1. Get drag-drop order from localStorage (most reliable)
		var rawOrder = localStorage.getItem(LOCAL_STORAGE_KEY);
		var orderedSelected = [];
		if (rawOrder) {
			try {
				var arr = JSON.parse(rawOrder);
				if (Array.isArray(arr)) {
					orderedSelected = arr.filter(x => typeof x === "string");
				}
			} catch (e) {}
		}

		// 2. Fallback: getSelectedColumns() if localStorage fails
		if (orderedSelected.length === 0) {
			orderedSelected = getSelectedColumns();
		}

		// 3. Build final config object
		var config = {
			filter_mode: columnFilterMode,
			selected_columns: orderedSelected,
			created_by: CURRENT_USER || '',
			created_at: CONFIG_CREATED_AT
		};

		try {
			await set_config_data(ADD_DOMAINS_CONFIG_KEY, config, API_BASE_URL);
			document.getElementById('config-save-status').innerHTML = "Configuration saved successfully.";
		} catch (e) {
			document.getElementById('config-save-status').innerHTML = "Failed to save configuration: " + e.message;
		}
	});
}

///////////////////////////////////////////////////////////////////////////////
