sort the code in meaningful way: const DATA_API_ENDPOINT = '/data.json';
const HEADER_ELEMENT = document.querySelector('header');
const ACTIONS_CONTAINER = document.querySelector('.actions-container');
const FORM_ELEMENT = document.querySelector('#form');
const TABLE_ELEMENT = document.querySelector('#table');

let BACKUP_DATA = [];
let CURRENT_DATA = [];
let HAS_UNSAVED_CHANGES = false;
const ACTIVE_ROW = { data: null, html: null };

const CHANGE_OBSERVER = new MutationObserver(function () {
    HAS_UNSAVED_CHANGES = true;
});
const OBSERVER_SETTINGS = { attributes: false, childList: true, subtree: true };

async function loadDataFromServer(url) {
    try {
        const response = await fetch(url);
        const data = await response.json();
        return data;
    } catch (error) {
        console.log(error);
        return [];
    }
}

function findDataItemIndexById(id) {
    return CURRENT_DATA.findIndex(item => item.id === id);
}

function exchangeArrayElements(arr, index1, index2) {
    const temp = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = temp;
}

function exchangeRowIndices(row1, row2) {
    const index1 = row1.children[1].textContent;
    const index2 = row2.children[1].textContent;

    row1.children[1].textContent = index2;
    row2.children[1].textContent = index1;
}

function backupCurrentData() {
    BACKUP_DATA = JSON.parse(JSON.stringify(CURRENT_DATA));
}

function clearActiveRowSelection() {
    ACTIVE_ROW.data = null;
    ACTIVE_ROW.html = null;
}

function restoreBackupData() {
    CURRENT_DATA = JSON.parse(JSON.stringify(BACKUP_DATA));
}

function sortTableData(property, direction, type) {
    CURRENT_DATA.sort((a, b) => {
        if (type === 'string') {
            return direction === 'asc'
                ? a[property].localeCompare(b[property], undefined, { numeric: true })
                : b[property].localeCompare(a[property], undefined, { numeric: true });
        } else if (type === 'number') {
            return direction === 'asc'
                ? a[property] - b[property]
                : b[property] - a[property];
        } else {
            console.log(`Unsupported type: ${type}`);
            return 0;
        }
    });
}

function fillFormFields(data) {
    FORM_ELEMENT.chemical_name.value = data.chemical_name;
    FORM_ELEMENT.vendor.value = data.vendor;
    FORM_ELEMENT.density.value = data.density;
    FORM_ELEMENT.viscosity.value = data.viscosity;
    FORM_ELEMENT.packaging.value = data.packaging;
    FORM_ELEMENT.pack_size.value = data.pack_size;
    FORM_ELEMENT.unit.value = data.unit;
    FORM_ELEMENT.quantity.value = data.quantity;
}

function toggleFormVisibility() {
    HEADER_ELEMENT.classList.toggle('show-form');
}

function createTableCell(text) {
    const cell = document.createElement('td');
    cell.textContent = text;
    return cell;
}

function createTableRow(obj, index) {
    const row = document.createElement('tr');

    const selectBox = createTableCell(`\u2714`);
    selectBox.classList.add('select-box');
    row.appendChild(selectBox);

    row.dataset.id = obj['id'];
    const rowIndexCell = createTableCell(index);
    row.appendChild(rowIndexCell);

    for (const key in obj) {
        if (key === 'id') continue;

        const cell = createTableCell(obj[key]);
        cell.dataset.property = key;
        row.appendChild(cell);
    }

    return row;
}

function generateTableBody(arrayOfObjs) {
    const fragment = document.createDocumentFragment();
    const tbody = document.createElement('tbody');
    fragment.appendChild(tbody);

    arrayOfObjs.forEach((obj, index) => {
        const row = createTableRow(obj, index + 1);
        tbody.appendChild(row);
    });
    return fragment;
}

function highlightSelectedRow(row) {
    const clickedRow = row;

    resetHeaderModes();

    if (clickedRow.classList.contains('active')) {
        clickedRow.classList.remove('active');
        clearActiveRowSelection();
        configureIdealMode();
    } else {
        const allRows = TABLE_ELEMENT.lastElementChild.children;
        for (let i = 0; i < allRows.length; i++) {
            allRows[i].classList.remove('active');
        }
        clickedRow.classList.add('active');
        ACTIVE_ROW.data = CURRENT_DATA[findDataItemIndexById(clickedRow.dataset.id)];
        ACTIVE_ROW.html = clickedRow;
        configureSelectedMode();
    }
}

function removeSelectedRow() {
    if (ACTIVE_ROW.data === null || ACTIVE_ROW.html === null) return;

    let currentRow = ACTIVE_ROW.html;
    let currentRowIndex = parseInt(currentRow.children[1].textContent);
    while (currentRow) {
        currentRow.children[1].textContent = currentRowIndex - 1;
        currentRowIndex++;
        currentRow = currentRow.nextElementSibling;
    }

    ACTIVE_ROW.html.remove();

    const deletedItemDataIndex = findDataItemIndexById(ACTIVE_ROW.data.id);
    CURRENT_DATA.splice(deletedItemDataIndex, 1);

    clearActiveRowSelection();
}

function moveSelectedRowUp() {
    if (ACTIVE_ROW.data === null || ACTIVE_ROW.html === null) return;

    const currentRow = ACTIVE_ROW.html;
    const previousRow = currentRow.previousElementSibling;

    if (previousRow) {
        const previousRowDataId = findDataItemIndexById(previousRow.dataset.id);
        currentRow.parentNode.insertBefore(currentRow, previousRow);
        exchangeRowIndices(previousRow, currentRow);
        exchangeArrayElements(CURRENT_DATA, previousRowDataId, previousRowDataId + 1);
    }
}

function moveSelectedRowDown() {
    if (ACTIVE_ROW.data === null || ACTIVE_ROW.html === null) return;

    const currentRow = ACTIVE_ROW.html;
    const nextRow = currentRow.nextElementSibling;

    if (nextRow) {
        const nextItemDataIndex = findDataItemIndexById(nextRow.dataset.id);
        currentRow.parentNode.insertBefore(nextRow, currentRow);
        exchangeRowIndices(nextRow, currentRow);
        exchangeArrayElements(CURRENT_DATA, nextItemDataIndex, nextItemDataIndex - 1);
    }
}

function renderTableContent(data) {
    const html = generateTableBody(data);
    TABLE_ELEMENT.lastElementChild.remove();
    TABLE_ELEMENT.append(html);
}

function handleRefreshAction() {
    if (HAS_UNSAVED_CHANGES) {
        const userConfirmation = window.confirm('Contains Unsaved Changes, Refresh?');
        if (!userConfirmation) return;
    }

    CHANGE_OBSERVER.disconnect();
    restoreBackupData();
    renderTableContent(CURRENT_DATA);
    resetHeaderModes();
    configureIdealMode();
    HAS_UNSAVED_CHANGES = false;
    CHANGE_OBSERVER.observe(TABLE_ELEMENT, OBSERVER_SETTINGS);
}

function handleSaveAction() {
    backupCurrentData();
    HAS_UNSAVED_CHANGES = false;
}

function enterEditMode() {
    FORM_ELEMENT.dataset.mode = 'edit';
    toggleFormVisibility();
    fillFormFields(ACTIVE_ROW.data);
}

function resetHeaderModes() {
    HEADER_ELEMENT.removeAttribute('class')
}

function configureIdealMode() {
    HEADER_ELEMENT.classList.add('show-toggle-form', 'show-refresh', 'show-save');
}

function configureSelectedMode() {
    HEADER_ELEMENT.classList.add('show-edit', 'show-delete', 'show-moveup', 'show-movedown', 'show-refresh', 'show-save');
}

function enableFormMode() {
    HEADER_ELEMENT.classList.add('show-toggle-form');
}

// init
loadDataFromServer(DATA_API_ENDPOINT)
    .then(res => {
        const resStr = JSON.stringify(res);
        BACKUP_DATA = JSON.parse(resStr);
        CURRENT_DATA = JSON.parse(resStr);

        const html = generateTableBody(CURRENT_DATA);
        TABLE_ELEMENT.append(html);

        TABLE_ELEMENT.addEventListener('click', function (e) {
            const clickedArea = e.target;

            if (clickedArea.classList.contains('select-box')) {
                highlightSelectedRow(clickedArea.parentElement);
            }

            if (clickedArea.dataset.sortProperty !== undefined) {
                const direction = clickedArea.dataset.sortDirection;
                sortTableData(clickedArea.dataset.sortProperty, direction, clickedArea.dataset.sortType);
                clickedArea.dataset.sortDirection = direction === "asc" ? "dsc" : "asc";

                clearActiveRowSelection();
                renderTableContent(CURRENT_DATA);
            }
        });

        ACTIONS_CONTAINER.addEventListener('click', function (e) {
            const button = e.target.closest('button');
            if (!button) return;

            const action = button.dataset.action;

            switch (action) {
                case 'edit':
                    enterEditMode();
                    break;

                case 'toggle-form':
                    toggleFormVisibility();
                    break;

                case 'moveup':
                    moveSelectedRowUp();
                    break;

                case 'movedown':
                    moveSelectedRowDown();
                    break;

                case 'delete':
                    removeSelectedRow();
                    break;

                case 'refresh':
                    handleRefreshAction();
                    break;

                case 'save':
                    handleSaveAction();
                    break;

                default:
                    return;
            }
        });

        FORM_ELEMENT.addEventListener('submit', function (e) {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData.entries());

            if (FORM_ELEMENT.dataset.mode === 'edit') {
                const id = ACTIVE_ROW.data.id;
                CURRENT_DATA[findDataItemIndexById(id)] = { id: id, ...data };
                FORM_ELEMENT.dataset.mode = 'add';
            } else {
                const id = `${new Date().getTime()}`;
                CURRENT_DATA.push({ id: id, ...data });
            }

            FORM_ELEMENT.reset();
            toggleFormVisibility();

            renderTableContent(CURRENT_DATA);
            clearActiveRowSelection();
            resetHeaderModes();
            configureIdealMode();
        });

        CHANGE_OBSERVER.observe(TABLE_ELEMENT, OBSERVER_SETTINGS);

    }).catch(function (e) {
        console.log(e);
    });