/**
 * domain-add.js
 * Add Domains tool — single and bulk CSV entry.
 *
 * Depends on common.js for:
 *   checkAuthSession, startAuthSessionMonitor, initEventButtons, showBody,
 *   sendCsvToAddApi_JS, get_config_data, set_config_data
 */

'use strict';

///////////////////////////////////////////////////////////////////////////////
// State
///////////////////////////////////////////////////////////////////////////////

var columnsMeta     = {};   // full column metadata from API
var selectedColumns = [];   // ordered list of active column names

///////////////////////////////////////////////////////////////////////////////
// Boot
///////////////////////////////////////////////////////////////////////////////

document.addEventListener('DOMContentLoaded', async function () {
    var loggedIn = await checkAuthSession();
    if (!loggedIn) return;

    startAuthSessionMonitor();
    initEventButtons();

    await loadServerConfig();
    await loadColumns();
    await loadCategories();

    initModeTabs();
    initSingleForm();
    initBulkForm();
    initClearButton();

    if (IS_ADMIN) {
        initColumnSearch();
        initSaveConfig();
    }

    setContentHeight();
    window.addEventListener('resize', setContentHeight);

    showBody();
});

///////////////////////////////////////////////////////////////////////////////
// Server Config
///////////////////////////////////////////////////////////////////////////////

async function loadServerConfig() {
    try {
        var raw = await get_config_data(ADD_DOMAINS_CONFIG_KEY, API_BASE_URL);
        if (!raw) return;
        var cfg = JSON.parse(raw);
        if (Array.isArray(cfg.selected_columns)) {
            selectedColumns = cfg.selected_columns.slice();
        }
    } catch (e) {
        // No config yet — defaults apply
    }
}

async function saveServerConfig() {
    var config = {
        selected_columns: selectedColumns.slice(),
        created_by:       CURRENT_USER || '',
        created_at:       CONFIG_CREATED_AT
    };
    await set_config_data(ADD_DOMAINS_CONFIG_KEY, config, API_BASE_URL);
}

///////////////////////////////////////////////////////////////////////////////
// Mode Tabs
///////////////////////////////////////////////////////////////////////////////

function initModeTabs() {
    document.querySelectorAll('.mode-tab').forEach(function (tab) {
        tab.addEventListener('click', function () {
            switchMode(tab.dataset.mode);
        });
    });
    switchMode('single');
}

function switchMode(mode) {
    var single = document.getElementById('single-add-container');
    var bulk   = document.getElementById('bulk-add-container');

    document.querySelectorAll('.mode-tab').forEach(function (tab) {
        tab.classList.toggle('active', tab.dataset.mode === mode);
    });

    if (mode === 'bulk') {
        single.style.display = 'none';
        bulk.style.display   = 'block';
        var ta = document.getElementById('bulk_csv');
        if (ta) ta.focus();
    } else {
        single.style.display = 'block';
        bulk.style.display   = 'none';
        var di = document.getElementById('domain');
        if (di) di.focus();
    }
}

///////////////////////////////////////////////////////////////////////////////
// Single Domain Form
///////////////////////////////////////////////////////////////////////////////

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

        var domain     = document.getElementById('domain').value.trim();
        var categoryId = document.getElementById('category_id').value;

        if (!domain) {
            setStatus('single', 'Please enter a domain name.', 'error');
            return;
        }

        setStatus('single', 'Adding domain…', 'loading');

        var headers = ['domain'].concat(selectedColumns);
        var row     = [domain];

        selectedColumns.forEach(function (col) {
            var input = document.getElementById('col_' + col);
            if (!input) { row.push(''); return; }
            row.push(input.type === 'checkbox' ? (input.checked ? '1' : '0') : input.value);
        });

        var csv    = headers.join(',') + '\n' + row.map(escapeCsvValue).join(',');
        var result = await sendCsvToAddApi_JS(csv, categoryId);

        if (result.status === 'ok') {
            if (result.added) {
                setStatus('single', '✓ ' + domain + ' added successfully.', 'success', false);
                clearSingleForm();
            } else {
                setStatus('single', '⚠ ' + domain + ' was not added — it may already exist in the portfolio.', 'warning', false);
            }
        } else {
            setStatus('single', '✗ Error: ' + (result.error || 'Unknown error.'), 'error', false);
            console.error(result);
        }
    });
}

///////////////////////////////////////////////////////////////////////////////
// Bulk CSV Form
///////////////////////////////////////////////////////////////////////////////

function initBulkForm() {
    document.getElementById('bulk-add-form').addEventListener('submit', async function (e) {
        if (!USE_JS_ADD_HANDLER) return;
        e.preventDefault();

        var text       = document.getElementById('bulk_csv').value.trim();
        var categoryId = document.getElementById('bulk_category_id').value;

        if (!text) {
            setStatus('bulk', 'Please enter at least one domain row.', 'error');
            return;
        }

        setStatus('bulk', 'Importing domains…', 'loading');

        var headers = ['domain'].concat(selectedColumns);
        var csv     = headers.join(',') + '\n';

        text.split('\n').forEach(function (line) {
            var trimmed = line.trim();
            if (!trimmed) return;
            var parts = trimmed.split(',');
            while (parts.length < headers.length) parts.push('');
            csv += parts.join(',') + '\n';
        });

        var result = await sendCsvToAddApi_JS(csv, categoryId);

        if (result.status === 'ok') {
            var firstDomain = text.split('\n')[0].split(',')[0].trim();
            var added = result.added || 0;
            var countMsg, countType;
            if (added === 0) {
                countMsg  = '⚠ No domains were added — they may already exist in the portfolio.';
                countType = 'warning';
            } else if (added === 1) {
                countMsg  = '✓ 1 domain (' + firstDomain + ') imported successfully.';
                countType = 'success';
            } else {
                countMsg  = '✓ ' + added + ' domains imported successfully, including ' + firstDomain + '.';
                countType = 'success';
            }
            setStatus('bulk', countMsg, countType, false);
        } else {
            setStatus('bulk', '✗ Error: ' + (result.error || 'Unknown error.'), 'error', false);
            console.error(result);
        }
    });
}

///////////////////////////////////////////////////////////////////////////////
// Categories
///////////////////////////////////////////////////////////////////////////////

async function loadCategories() {
    try {
        var res  = await fetch(API_BASE_URL + '?c=list&t=category&oper=user', { credentials: 'same-origin' });
        var data = await res.json();
        if (!data || !Array.isArray(data.ids)) return;

        var s1 = document.getElementById('category_id');
        var s2 = document.getElementById('bulk_category_id');

        data.ids.forEach(function (cat) {
            if (s1) s1.appendChild(makeCatOption(cat));
            if (s2) s2.appendChild(makeCatOption(cat));
        });
    } catch (e) { /* dropdowns stay at "No category" */ }
}

function makeCatOption(cat) {
    var opt       = document.createElement('option');
    opt.value     = cat.id;
    opt.textContent = cat.name;
    return opt;
}

///////////////////////////////////////////////////////////////////////////////
// Column Loading
///////////////////////////////////////////////////////////////////////////////

async function loadColumns() {
    try {
        var res  = await fetch(API_BASE_URL + '?c=list&t=domain&oper=columns', { credentials: 'same-origin' });
        var data = await res.json();
        if (!data || !data.columns) return;

        columnsMeta = data.columns;

        if (IS_ADMIN) {
            renderColumnList();
        }

        syncHiddenFields();
        renderExtraFields();
        renderBulkColumnOrder();

    } catch (e) {
        var el = document.getElementById('columns-list');
        if (el) el.textContent = 'Error loading columns.';
    }
}

///////////////////////////////////////////////////////////////////////////////
// Admin Sidebar Column List
///////////////////////////////////////////////////////////////////////////////

function getEligibleColumns() {
    return Object.keys(columnsMeta).filter(function (colName) {
        var col = columnsMeta[colName];
        if (!col) return false;
        if (!(col.editable == 1 || col.editable === true)) return false;
        if (!(col.gridview == 1 || col.gridview === true)) return false;
        if (EXCLUDED_COLUMNS.indexOf(colName) !== -1) return false;
        return true;
    });
}

function renderColumnList(filterText) {
    var container = document.getElementById('columns-list');
    if (!container) return;

    container.innerHTML = '';

    var eligible    = getEligibleColumns();
    var selectedSet = new Set(selectedColumns);
    var search      = (filterText || '').toLowerCase().trim();

    // Selected columns first (in saved order), then unselected alphabetically
    var ordered = selectedColumns
        .filter(function (c) { return eligible.indexOf(c) !== -1; })
        .concat(
            eligible
                .filter(function (c) { return !selectedSet.has(c); })
                .sort()
        );

    ordered.forEach(function (colName) {
        var col       = columnsMeta[colName] || {};
        var labelText = (col.label && col.label.trim()) ? col.label : autoLabel(colName);

        // Apply search filter
        if (search && labelText.toLowerCase().indexOf(search) === -1 && colName.toLowerCase().indexOf(search) === -1) {
            return;
        }

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

        var checkbox     = document.createElement('input');
        checkbox.type    = 'checkbox';
        checkbox.value   = colName;
        checkbox.checked = selectedSet.has(colName);
        checkbox.id      = 'chk_' + colName;
        checkbox.addEventListener('change', onColumnToggle);

        var labelWrap        = document.createElement('label');
        labelWrap.htmlFor    = 'chk_' + colName;
        labelWrap.className  = 'columns-list-label';

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

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

        labelWrap.appendChild(labelMain);
        labelWrap.appendChild(labelKey);

        item.appendChild(checkbox);
        item.appendChild(labelWrap);
        container.appendChild(item);

        if (checkbox.checked) item.setAttribute('draggable', 'true');
    });

    enableDragAndDrop();
}

function onColumnToggle() {
    rebuildSelectedFromDOM();
    syncHiddenFields();
    renderExtraFields();
    renderBulkColumnOrder();
    renderColumnList(getCurrentSearch());
}

function rebuildSelectedFromDOM() {
    var container = document.getElementById('columns-list');
    if (!container) return;
    selectedColumns = [];
    container.querySelectorAll('.columns-list-item').forEach(function (item) {
        var cb = item.querySelector('input[type="checkbox"]');
        if (cb && cb.checked) {
            selectedColumns.push(cb.value);
        }
        if (cb) item.setAttribute('draggable', cb.checked ? 'true' : 'false');
    });
}

///////////////////////////////////////////////////////////////////////////////
// Column Search Filter
///////////////////////////////////////////////////////////////////////////////

function initColumnSearch() {
    var input = document.getElementById('column-search');
    if (!input) return;
    input.addEventListener('input', function () {
        renderColumnList(this.value);
    });
}

function getCurrentSearch() {
    var input = document.getElementById('column-search');
    return input ? input.value : '';
}

///////////////////////////////////////////////////////////////////////////////
// Save Config Button
///////////////////////////////////////////////////////////////////////////////

function initSaveConfig() {
    var btn    = document.getElementById('export-config-btn');
    var status = document.getElementById('config-save-status');
    if (!btn) return;

    btn.addEventListener('click', async function () {
        btn.disabled      = true;
        status.textContent = 'Saving…';
        status.className   = 'submit-status-text loading';
        try {
            await saveServerConfig();
            status.textContent = '✓ Saved for all users.';
            status.className   = 'submit-status-text success';
        } catch (e) {
            status.textContent = '✗ Save failed: ' + e.message;
            status.className   = 'submit-status-text error';
        } finally {
            btn.disabled = false;
        }
    });
}

///////////////////////////////////////////////////////////////////////////////
// Drag and Drop Reorder
///////////////////////////////////////////////////////////////////////////////

function enableDragAndDrop() {
    var container = document.getElementById('columns-list');
    if (!container) return;

    var dragging = null;

    container.querySelectorAll('.columns-list-item').forEach(function (item) {
        item.addEventListener('dragstart', function (e) {
            var cb = item.querySelector('input[type="checkbox"]');
            if (!cb || !cb.checked) { e.preventDefault(); return; }
            dragging = item;
            setTimeout(function () { item.classList.add('dragging'); }, 0);
        });

        item.addEventListener('dragend', function () {
            item.classList.remove('dragging');
            dragging = null;
            rebuildSelectedFromDOM();
            syncHiddenFields();
            renderExtraFields();
            renderBulkColumnOrder();
        });

        item.addEventListener('dragover', function (e) {
            e.preventDefault();
            if (!dragging || dragging === item) return;
            var cb = item.querySelector('input[type="checkbox"]');
            if (!cb || !cb.checked) return;
            var after = e.clientY > item.getBoundingClientRect().top + item.getBoundingClientRect().height / 2;
            container.insertBefore(dragging, after ? item.nextSibling : item);
        });
    });
}

///////////////////////////////////////////////////////////////////////////////
// Extra Fields (Single Form)
///////////////////////////////////////////////////////////////////////////////

function syncHiddenFields() {
    var h1 = document.getElementById('extra_columns');
    var h2 = document.getElementById('bulk_extra_columns');
    var val = selectedColumns.join(',');
    if (h1) h1.value = val;
    if (h2) h2.value = val;
}

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

    selectedColumns.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 lMain         = document.createElement('span');
        lMain.textContent = labelText + ' ';

        var lKey          = document.createElement('span');
        lKey.className    = 'field-key';
        lKey.textContent  = '(' + colName + ')';

        label.appendChild(lMain);
        label.appendChild(lKey);

        var input = buildInput(colName, fieldType);

        // Restore any posted values
        if (POSTED_VALUES && POSTED_VALUES.hasOwnProperty('col_' + colName)) {
            var val = POSTED_VALUES['col_' + colName];
            if (input.type === 'checkbox') input.checked = (val !== '' && val !== '0');
            else input.value = val;
        }

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

function buildInput(colName, fieldType) {
    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;
    return input;
}

///////////////////////////////////////////////////////////////////////////////
// Bulk Column Order
///////////////////////////////////////////////////////////////////////////////

function renderBulkColumnOrder() {
    var container = document.getElementById('bulk-column-order');
    var textarea  = document.getElementById('bulk_csv');
    if (!container) return;

    var cols = ['domain'].concat(selectedColumns);

    container.innerHTML = '';
    cols.forEach(function (col, i) {
        var meta  = columnsMeta[col];
        var label = col === 'domain'
            ? 'domain'
            : (meta && meta.label && meta.label.trim() ? meta.label : autoLabel(col));

        var pill         = document.createElement('span');
        pill.className   = 'column-pill';
        pill.textContent = (i + 1) + '. ' + label;
        container.appendChild(pill);
    });

    if (textarea) {
        var r1 = cols.map(function (c, i) { return i === 0 ? 'example.com' : 'value'; }).join(', ');
        var r2 = cols.map(function (c, i) { return i === 0 ? 'example.net' : 'value'; }).join(', ');
        textarea.placeholder = r1 + '\n' + r2;
    }
}

///////////////////////////////////////////////////////////////////////////////
// Clear Button
///////////////////////////////////////////////////////////////////////////////

function initClearButton() {
    var btn = document.getElementById('clear-form-btn');
    if (!btn) return;
    btn.addEventListener('click', clearSingleFormAndStatus);
}

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

function clearSingleFormAndStatus() {
    clearSingleForm();
    setStatus('single', '', '');
}

///////////////////////////////////////////////////////////////////////////////
// Status
///////////////////////////////////////////////////////////////////////////////

var statusTimers = {};

function setStatus(mode, message, type, autoClear) {
    var el = document.getElementById(
        mode === 'bulk' ? 'bulk-domain-add-status' : 'single-domain-add-status'
    );
    if (!el) return;

    // Cancel any pending auto-clear for this mode
    if (statusTimers[mode]) {
        clearTimeout(statusTimers[mode]);
        statusTimers[mode] = null;
    }

    el.textContent = message;
    el.className   = 'submit-status-text' + (type ? ' ' + type : '');

    // Auto-clear success and warning messages after 6 seconds
    if (autoClear !== false && (type === 'success' || type === 'warning')) {
        statusTimers[mode] = setTimeout(function () {
            el.textContent = '';
            el.className   = 'submit-status-text';
        }, 6000);
    }
}

///////////////////////////////////////////////////////////////////////////////
// Layout
///////////////////////////////////////////////////////////////////////////////

function setContentHeight() {
    var header = document.getElementById('appheader');
    if (!header) return;
    // offsetHeight is more reliable than getBoundingClientRect during early load
    var h = header.offsetHeight;
    if (h > 0) {
        document.documentElement.style.setProperty('--appheader-height', h + 'px');
    }
}

// Re-measure once all assets (logo image) have loaded
window.addEventListener('load', setContentHeight);

///////////////////////////////////////////////////////////////////////////////
// Helpers
///////////////////////////////////////////////////////////////////////////////

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

function escapeCsvValue(val) {
    if (val === null || val === undefined) return '';
    val = String(val);
    if (val.indexOf(',') !== -1 || val.indexOf('"') !== -1 || val.indexOf('\n') !== -1) {
        return '"' + val.replace(/"/g, '""') + '"';
    }
    return val;
}