/**
 * @file configButton.js
 * @description Hanterar Config-knappen och modal för att välja vilka statusar som visas
 * 
 * Author: Linus Olofsson - Iver
 * Date: 2026-02-27
 * 
 * @purpose Låter användaren konfigurera vilka ticket-statusar som ska visas i listan
 * @invoked_by popup.js
 */

// Alla tillgängliga titlar för article check (matchar ARTICLE_GUID_MAP i ticketApi.js)
const AVAILABLE_TITLES = [
    'Junior Technical Consultant',
    'Technical Consultant',
    'Senior Technical Consultant',
    'Specialist',
    'Senior Specialist',
    'Project Manager',
    'Senior Project Manager',
];

// Alla kända Spark-statusar med ID och namn (från status.txt)
const ALL_STATUSES = [
    { id: '3efc9f1f-0000-0000-486b-0f2700000000', description: 'New' },
    { id: '3efc9f1f-0000-0000-5b4f-1b3b00000000', description: 'Received' },
    { id: '3efc9f1f-0000-0000-6e33-270f00000000', description: 'Pågående' },
    { id: '3efc9f1f-0000-0000-8117-332300000000', description: 'Waiting for supplier' },
    { id: '3efc9f1f-0000-0000-a7df-4a0b00000000', description: 'Waiting for customer' },
    { id: '3efc9f1f-0000-0000-bac3-561f00000000', description: 'Ready for customer' },
    { id: '3efc9f1f-0000-0000-8346-992900000000', description: 'To be specified' },
    { id: '3efc9f1f-0000-0000-962a-a53d00000000', description: 'Planned' },
    { id: '3efc9f1f-0000-0000-a90e-b11100000000', description: 'Queued' },
    { id: '3efc9f1f-0000-0000-bcf2-bc2500000000', description: 'Not approved' },
    { id: '3efc9f1f-0000-0000-e2ba-d40d00000000', description: 'Ready for testning' },
    { id: '3efc9f1f-0000-0000-f59e-e02100000000', description: 'Ready for deployment' },
    { id: '3efc9f1f-0000-0000-0883-ec3500000000', description: 'Ready from iPlace' },
    { id: '3efc9f1f-0000-0000-1b67-f80900000000', description: 'Ready from iService' },
    { id: '3efc9f1f-0000-0000-877e-9d1e00000000', description: 'Routine work' },
    { id: '3efc9f1f-0000-0000-0cbb-f02a00000000', description: 'Ready from Develop' },
    { id: '3efc9f1f-0000-0000-1f9f-fc3e00000000', description: 'Ready from iSpeak' },
    { id: '3efc9f1f-0000-0000-3d0a-f00800000000', description: 'Updated by customer' },
    { id: '3efc9f1f-0000-0000-b17e-b93b00000000', description: 'Waiting for decision' },
    { id: '3efc9f1f-0000-0000-5fad-e70700000000', description: 'Ready from Sales' },
    { id: '3efc9f1f-0000-0000-dc8c-163600000000', description: "Waiting for the customer's supplier" },
    { id: '3efc9f1f-0000-0000-ef70-220a00000000', description: 'Waiting for serviceteam' },
    { id: '3efc9f1f-0000-0000-8791-812a00000000', description: 'Delivery in progress' },
    { id: '3efc9f1f-0000-0000-c03d-a52600000000', description: 'Updated by i247' },
    { id: '3efc9f1f-0000-0000-d321-b13a00000000', description: 'Updated internally' },
    { id: '3efc9f1f-0000-0000-e605-bd0e00000000', description: 'Ready from warehouse' },
    { id: '3efc9f1f-0000-0000-0cce-d43600000000', description: 'Analyzing' },
    { id: '3efc9f1f-0000-0000-1fb2-e00a00000000', description: 'Evaluated' },
    { id: '3efc9f1f-0000-0000-457a-f83200000000', description: 'Solved' },
    { id: '3efc9f1f-0000-0000-585e-040700000000', description: 'Utford' },
    { id: '3efc9f1f-0000-0000-6b42-101b00000000', description: 'Submitted' },
    { id: '3efc9f1f-0000-0000-7e26-1c2f00000000', description: 'Draft' },
    { id: '3efc9f1f-0000-0000-910a-280300000000', description: 'Waiting for approval' },
    { id: '3efc9f1f-0000-0000-a4ee-331700000000', description: 'On Hold' },
    { id: '3efc9f1f-0000-0000-b7d2-3f2b00000000', description: 'Utford med avvikelser' },
    { id: '3efc9f1f-0000-0000-cab6-4b3f00000000', description: 'Ej Utford/ Misslyckad' },
    { id: '3efc9f1f-0000-0000-dd9a-571300000000', description: 'Waiting for approval (2)' },
];

// Statusar som VISAS som standard (checked)
const DEFAULT_SHOWN_IDS = new Set([
    '3efc9f1f-0000-0000-486b-0f2700000000', // New
    '3efc9f1f-0000-0000-5b4f-1b3b00000000', // Received
    '3efc9f1f-0000-0000-a7df-4a0b00000000', // Waiting for customer
    '3efc9f1f-0000-0000-3d0a-f00800000000', // Updated by customer
    '3efc9f1f-0000-0000-962a-a53d00000000', // Planned
    '3efc9f1f-0000-0000-6e33-270f00000000', // Pågående
]);

// Standard exkluderade = alla som INTE är i DEFAULT_SHOWN_IDS
const DEFAULT_EXCLUDED_IDS = ALL_STATUSES
    .filter(s => !DEFAULT_SHOWN_IDS.has(s.id))
    .map(s => s.id);

/**
 * Hämta användarens exkluderade status-ID:n från storage.
 * Om inget sparat, returnera default-listan.
 */
async function getExcludedStatusIds() {
    try {
        const result = await chrome.storage.local.get(['configExcludedStatusIds']);
        if (result.configExcludedStatusIds && Array.isArray(result.configExcludedStatusIds)) {
            return result.configExcludedStatusIds;
        }
    } catch (e) {
        console.warn('Could not load config:', e);
    }
    return [...DEFAULT_EXCLUDED_IDS];
}

/**
 * Spara användarens exkluderade status-ID:n till storage.
 */
async function saveExcludedStatusIds(excludedIds) {
    await chrome.storage.local.set({ configExcludedStatusIds: excludedIds });
}

/**
 * Hämta användarens valda sortering från storage.
 * Default: 'latestChange'
 */
async function getSortBy() {
    try {
        const result = await chrome.storage.local.get(['configSortBy']);
        if (result.configSortBy) {
            return result.configSortBy;
        }
    } catch (e) {
        console.warn('Could not load sort config:', e);
    }
    return 'latestChange';
}

/**
 * Spara användarens valda sortering till storage.
 */
async function saveSortBy(sortBy) {
    await chrome.storage.local.set({ configSortBy: sortBy });
}

/**
 * Hämta om tidrapport artikel-kontroll är påslagen.
 * Default: true (på)
 */
async function getTimereportNotice() {
    try {
        const result = await chrome.storage.local.get(['configTimereportNotice']);
        if (typeof result.configTimereportNotice === 'boolean') {
            return result.configTimereportNotice;
        }
    } catch (e) {
        console.warn('Could not load timereport notice config:', e);
    }
    return true;
}

/**
 * Spara tidrapport artikel-kontroll toggle till storage.
 */
async function saveTimereportNotice(enabled) {
    await chrome.storage.local.set({ configTimereportNotice: enabled });
}

/**
 * Hämta sparad title override från storage.
 * Returnerar tom sträng om ingen override (= använd JWT-titel).
 */
async function getTitleOverride() {
    try {
        const result = await chrome.storage.local.get(['configTitleOverride']);
        if (typeof result.configTitleOverride === 'string') {
            return result.configTitleOverride;
        }
    } catch (e) {
        console.warn('Could not load title override config:', e);
    }
    return '';
}

/**
 * Spara title override till storage.
 */
async function saveTitleOverride(title) {
    await chrome.storage.local.set({ configTitleOverride: title });
}

/**
 * Hämta Custom Queue config från storage.
 * Returnerar { enabled: bool, viewIds: string[] }
 */
async function getCustomQueueConfig() {
    try {
        const result = await chrome.storage.local.get(['configCustomQueueEnabled', 'configCustomQueueViewIds']);
        return {
            enabled: result.configCustomQueueEnabled === true,
            viewIds: Array.isArray(result.configCustomQueueViewIds) ? result.configCustomQueueViewIds : []
        };
    } catch (e) {
        console.warn('Could not load custom queue config:', e);
    }
    return { enabled: false, viewIds: [] };
}

/**
 * Spara Custom Queue config till storage.
 */
async function saveCustomQueueConfig(enabled, viewIds) {
    await chrome.storage.local.set({
        configCustomQueueEnabled: enabled,
        configCustomQueueViewIds: viewIds
    });
}

/**
 * Hämta SavedViews via message bridge till service worker.
 * Returnerar array av view-objekt.
 */
async function fetchSavedViewsFromBridge() {
    return new Promise((resolve) => {
        chrome.runtime.sendMessage({ action: 'getSavedViews' }, (response) => {
            if (chrome.runtime.lastError) {
                console.error('Error fetching saved views:', chrome.runtime.lastError);
                resolve([]);
                return;
            }
            if (response && response.success) {
                resolve(response.views || []);
            } else {
                console.error('Failed to fetch saved views:', response?.error);
                resolve([]);
            }
        });
    });
}

/**
 * Hämta om minimal-läge är aktiverat.
 * Default: false (av)
 */
async function getMinimalMode() {
    try {
        const result = await chrome.storage.local.get(['configMinimalMode']);
        if (typeof result.configMinimalMode === 'boolean') {
            return result.configMinimalMode;
        }
    } catch (e) {
        console.warn('Could not load minimal mode config:', e);
    }
    return false;
}

/**
 * Spara minimal-läge toggle till storage.
 */
async function saveMinimalMode(enabled) {
    await chrome.storage.local.set({ configMinimalMode: enabled });
}

/**
 * Initiera Config-knappen och dess modal
 */
function initConfigButton() {
    const configBtn = document.getElementById('configBtn');
    const configModal = document.getElementById('configModal');
    const saveConfigBtn = document.getElementById('saveConfigButton');
    const cancelConfigBtn = document.getElementById('cancelConfigButton');
    const statusCheckboxes = document.getElementById('statusCheckboxes');

    if (!configBtn || !configModal) {
        console.warn('Config button or modal not found in DOM');
        return;
    }

    const timereportToggle = document.getElementById('timereportNoticeToggle');
    const minimalToggle = document.getElementById('minimalModeToggle');
    const titleOverrideSelect = document.getElementById('titleOverrideSelect');
    const currentTitleLabel = document.getElementById('currentTitleLabel');
    const customQueueToggle = document.getElementById('customQueueToggle');
    const customQueueSelector = document.getElementById('customQueueSelector');
    const customQueueCheckboxes = document.getElementById('customQueueCheckboxes');

    // Populera title override dropdown med alla tillgängliga titlar
    if (titleOverrideSelect) {
        for (const title of AVAILABLE_TITLES) {
            const opt = document.createElement('option');
            opt.value = title;
            opt.textContent = title;
            titleOverrideSelect.appendChild(opt);
        }
    }

    // Öppna modal
    configBtn.addEventListener('click', async () => {
        const excludedIds = await getExcludedStatusIds();
        renderCheckboxes(statusCheckboxes, excludedIds);

        // Sätt rätt radio-knapp för sortering
        const currentSort = await getSortBy();
        const sortRadio = configModal.querySelector(`input[name="sortBy"][value="${currentSort}"]`);
        if (sortRadio) sortRadio.checked = true;

        // Sätt toggle för tidrapport-notifikationer
        if (timereportToggle) {
            timereportToggle.checked = await getTimereportNotice();
        }

        // Sätt title override dropdown och Current Title label
        if (titleOverrideSelect) {
            const savedOverride = await getTitleOverride();
            titleOverrideSelect.value = savedOverride;
            updateCurrentTitleLabel(savedOverride);
        }

        // Sätt toggle för minimal-läge
        if (minimalToggle) {
            minimalToggle.checked = await getMinimalMode();
        }

        // Sätt Custom Queue toggle och ladda vyer
        if (customQueueToggle && customQueueSelector && customQueueCheckboxes) {
            const cqConfig = await getCustomQueueConfig();
            customQueueToggle.checked = cqConfig.enabled;
            customQueueSelector.classList.toggle('hidden', !cqConfig.enabled);

            if (cqConfig.enabled) {
                await populateCustomQueueCheckboxes(customQueueCheckboxes, cqConfig.viewIds);
            }
        }

        configModal.classList.remove('hidden');
    });

    // Spara
    saveConfigBtn.addEventListener('click', async () => {
        const excludedIds = collectExcludedFromCheckboxes(statusCheckboxes);
        await saveExcludedStatusIds(excludedIds);

        // Spara sortering
        const selectedSort = configModal.querySelector('input[name="sortBy"]:checked');
        if (selectedSort) {
            await saveSortBy(selectedSort.value);
            console.log('Config saved, sort by:', selectedSort.value);
        }

        // Spara tidrapport-notifikationer toggle
        if (timereportToggle) {
            await saveTimereportNotice(timereportToggle.checked);
            console.log('Config saved, timereport notice:', timereportToggle.checked);
        }

        // Spara title override
        if (titleOverrideSelect) {
            await saveTitleOverride(titleOverrideSelect.value);
            console.log('Config saved, title override:', titleOverrideSelect.value || '(automatic)');
        }

        // Spara Custom Queue config
        if (customQueueToggle && customQueueCheckboxes) {
            const selectedViewIds = [];
            const cqCbs = customQueueCheckboxes.querySelectorAll('input[type="checkbox"]');
            for (const cb of cqCbs) {
                if (cb.checked) selectedViewIds.push(cb.value);
            }
            await saveCustomQueueConfig(customQueueToggle.checked, selectedViewIds);
            console.log('Config saved, custom queue:', customQueueToggle.checked, 'views:', selectedViewIds.length);
        }

        // Spara minimal-läge toggle + applicera direkt
        if (minimalToggle) {
            await saveMinimalMode(minimalToggle.checked);
            const container = document.querySelector('.container');
            if (container) {
                container.classList.toggle('minimal', minimalToggle.checked);
            }
            console.log('Config saved, minimal mode:', minimalToggle.checked);
        }

        configModal.classList.add('hidden');
        console.log('Config saved, excluded statuses:', excludedIds.length);
    });

    // Avbryt
    cancelConfigBtn.addEventListener('click', () => {
        configModal.classList.add('hidden');
    });

    // Uppdatera Current Title label vid dropdown-ändring
    if (titleOverrideSelect) {
        titleOverrideSelect.addEventListener('change', () => {
            updateCurrentTitleLabel(titleOverrideSelect.value);
        });
    }

    // Custom Queue toggle: visa/dölj selector och ladda vyer vid behov
    if (customQueueToggle && customQueueSelector && customQueueCheckboxes) {
        customQueueToggle.addEventListener('change', async () => {
            const isOn = customQueueToggle.checked;
            customQueueSelector.classList.toggle('hidden', !isOn);

            if (isOn && customQueueCheckboxes.children.length === 0) {
                const cqConfig = await getCustomQueueConfig();
                await populateCustomQueueCheckboxes(customQueueCheckboxes, cqConfig.viewIds);
            }
        });
    }

    // Stäng modal vid klick på overlay
    const overlay = configModal.querySelector('.modal-overlay');
    if (overlay) {
        overlay.addEventListener('click', () => {
            configModal.classList.add('hidden');
        });
    }
}

/**
 * Rendera checkboxar i modalen.
 * Checked = statusen VISAS (dvs är INTE exkluderad).
 */
function renderCheckboxes(container, excludedIds) {
    container.innerHTML = '';

    for (const status of ALL_STATUSES) {
        const isExcluded = excludedIds.includes(status.id);

        const label = document.createElement('label');
        label.className = 'config-checkbox-label';

        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.value = status.id;
        checkbox.checked = !isExcluded; // Checked = visa, Unchecked = dölj

        const span = document.createElement('span');
        span.textContent = status.description;

        label.appendChild(checkbox);
        label.appendChild(span);
        container.appendChild(label);
    }
}

/**
 * Samla ihop vilka statusar som ska exkluderas (unchecked = exkluderad).
 */
function collectExcludedFromCheckboxes(container) {
    const excludedIds = [];
    const checkboxes = container.querySelectorAll('input[type="checkbox"]');
    for (const cb of checkboxes) {
        if (!cb.checked) {
            excludedIds.push(cb.value);
        }
    }
    return excludedIds;
}

/**
 * Uppdatera "Current Title" label baserat på vald override eller JWT-titel.
 */
function updateCurrentTitleLabel(overrideValue) {
    const label = document.getElementById('currentTitleLabel');
    if (!label) return;

    if (overrideValue) {
        label.textContent = `Current Title: ${overrideValue}`;
    } else {
        // Fallback: läs JWT-titeln från DOM
        const userTitleEl = document.getElementById('userTitle');
        const jwtTitle = userTitleEl ? userTitleEl.textContent.replace('Title: ', '') : '--';
        label.textContent = `Current Title: ${jwtTitle} (from token)`;
    }
}

/**
 * Populera Custom Queue checkboxar med SavedViews från API.
 * @param {HTMLElement} container - Elementet där checkboxarna renderas
 * @param {string[]} selectedViewIds - Tidigare sparade view-IDs som ska vara checkade
 */
async function populateCustomQueueCheckboxes(container, selectedViewIds) {
    container.innerHTML = '<p class="config-custom-queue-loading">Loading queues...</p>';

    const views = await fetchSavedViewsFromBridge();

    container.innerHTML = '';

    if (!views || views.length === 0) {
        container.innerHTML = '<p class="config-custom-queue-loading">No queues found.</p>';
        return;
    }

    const selectedSet = new Set(selectedViewIds);

    for (const view of views) {
        const label = document.createElement('label');
        label.className = 'config-custom-queue-label';

        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.value = view.id;
        checkbox.checked = selectedSet.has(view.id);

        const span = document.createElement('span');
        span.textContent = view.name;
        span.title = `${view.name} (${view.ownerDisplayName})`;

        label.appendChild(checkbox);
        label.appendChild(span);
        container.appendChild(label);
    }
}

export { initConfigButton, getExcludedStatusIds, getSortBy, getTimereportNotice, getMinimalMode, getTitleOverride, getCustomQueueConfig, ALL_STATUSES, DEFAULT_EXCLUDED_IDS };
