<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>

<?= message_box('success'); ?>
<?= message_box('error'); ?>

<?php
$dashboard_initial_module = !empty($dashboard_initial_module) ? $dashboard_initial_module : 'overview';
$dashboard_initial_html = isset($dashboard_initial_html) ? $dashboard_initial_html : '';
$dashboard_user_id = isset($dashboard_user_id) ? (int) $dashboard_user_id : 0;

$header_actions = ''
    . '<span class="erp-badge erp-badge--neutral"><i data-lucide="calendar-days" class="h-3.5 w-3.5"></i><span>' . date('M d, Y') . '</span></span>'
    . '<button type="button" class="erp-btn" data-dashboard-refresh-active><i data-lucide="refresh-cw" class="h-4 w-4"></i><span>Refresh</span></button>'
    . '<a href="' . base_url('admin/dashboard/reset_cache') . '" class="erp-btn"><i data-lucide="database" class="h-4 w-4"></i><span>' . lang('reset_cache') . '</span></a>';
?>

<div
    class="erp-page"
    data-dashboard-shell
    data-module-url="<?= html_escape($dashboard_module_url) ?>"
    data-initial-module="<?= html_escape($dashboard_initial_module) ?>"
    data-user-id="<?= (int) $dashboard_user_id ?>"
>
    <section class="erp-panel">
        <div class="border-b border-border px-3 py-2">
            <div class="erp-tabs" data-dashboard-tabs>
                <?php foreach ($dashboard_modules as $moduleKey => $moduleInfo): ?>
                    <button
                        type="button"
                        data-dashboard-tab="<?= html_escape($moduleKey) ?>"
                        data-dashboard-label="<?= html_escape($moduleInfo['label']) ?>"
                        draggable="true"
                        title="<?= lang('drag_reorder_tabs') ?>"
                        class="erp-tab<?= $moduleKey === $dashboard_initial_module ? ' erp-tab--active' : '' ?>"
                    >
                        <i data-lucide="<?= html_escape($moduleInfo['icon']) ?>" class="h-4 w-4"></i>
                        <span><?= html_escape($moduleInfo['label']) ?></span>
                    </button>
                <?php endforeach; ?>
            </div>
        </div>

        <?php foreach ($dashboard_modules as $moduleKey => $moduleInfo): ?>
            <section
                data-dashboard-panel="<?= html_escape($moduleKey) ?>"
                class="<?= $moduleKey === $dashboard_initial_module ? '' : 'hidden ' ?>"
            >
                <?= $this->load->view('admin/common/erp/section_header', array(
                    'title' => $moduleInfo['label'],
                    'subtitle' => $moduleKey === 'overview'
                        ? 'Immediate operating position with dense KPIs and watchlists.'
                        : 'Live module snapshot loaded on demand.',
                    'actions' => '<button type="button" data-dashboard-refresh-panel="' . html_escape($moduleKey) . '" class="erp-btn"><i data-lucide="refresh-cw" class="h-4 w-4"></i><span>Refresh Module</span></button>',
                ), true); ?>

                <div
                    class="erp-panel-body"
                    data-dashboard-panel-body="<?= html_escape($moduleKey) ?>"
                    <?= $moduleKey === $dashboard_initial_module && $dashboard_initial_html !== '' ? 'data-dashboard-prefilled="1"' : '' ?>
                >
                    <?php if ($moduleKey === $dashboard_initial_module && $dashboard_initial_html !== '') { ?>
                        <?= $dashboard_initial_html; ?>
                    <?php } else { ?>
                        <div class="dashboard-module-skeleton space-y-3">
                            <div class="grid grid-cols-2 gap-3 xl:grid-cols-4 2xl:grid-cols-8">
                                <?php for ($i = 0; $i < 8; $i++): ?>
                                    <div class="animate-pulse rounded-xl border border-border bg-background/60 p-3">
                                        <div class="h-3 w-16 rounded bg-muted"></div>
                                        <div class="mt-3 h-6 w-20 rounded bg-muted"></div>
                                        <div class="mt-2 h-3 w-24 rounded bg-muted"></div>
                                    </div>
                                <?php endfor; ?>
                            </div>
                            <div class="grid grid-cols-1 gap-3 xl:grid-cols-[minmax(0,1.4fr)_minmax(320px,0.9fr)]">
                                <div class="animate-pulse rounded-xl border border-border bg-background/60 p-3">
                                    <div class="h-4 w-36 rounded bg-muted"></div>
                                    <div class="mt-3 h-[220px] rounded-xl bg-muted/80"></div>
                                </div>
                                <div class="grid gap-3">
                                    <div class="animate-pulse rounded-xl border border-border bg-background/60 p-3">
                                        <div class="h-4 w-28 rounded bg-muted"></div>
                                        <div class="mt-3 h-[104px] rounded-xl bg-muted/80"></div>
                                    </div>
                                    <div class="animate-pulse rounded-xl border border-border bg-background/60 p-3">
                                        <div class="h-4 w-32 rounded bg-muted"></div>
                                        <div class="mt-3 h-[104px] rounded-xl bg-muted/80"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php } ?>
                </div>
            </section>
        <?php endforeach; ?>
    </section>
</div>

<script>
document.addEventListener("DOMContentLoaded", () => {
    const shell = document.querySelector("[data-dashboard-shell]");
    if (!shell) {
        return;
    }

    const moduleBaseUrl = shell.dataset.moduleUrl || "";
    const initialModule = shell.dataset.initialModule || "overview";
    const dashboardUserId = shell.dataset.userId || "0";
    const tabsContainer = document.querySelector("[data-dashboard-tabs]");
    const tabs = Array.from(document.querySelectorAll("[data-dashboard-tab]"));
    const panels = Array.from(document.querySelectorAll("[data-dashboard-panel]"));
    const panelRefreshButtons = Array.from(document.querySelectorAll("[data-dashboard-refresh-panel]"));
    const refreshActiveButton = document.querySelector("[data-dashboard-refresh-active]");
    const requests = new Map();
    const loaded = new Set();
    const moduleCacheKey = "erp_dashboard_module_cache_v1";
    const moduleCacheTtl = 120000;
    const moduleOrderKey = `erp_dashboard_tab_order_v1_${dashboardUserId}`;
    let activeModule = initialModule;
    let draggedModule = null;

    const updateIcons = (root) => {
        if (window.lucide && typeof window.lucide.createIcons === "function") {
            window.lucide.createIcons({ attrs: { "stroke-width": 1.75 }, root });
        }
    };

    const getModuleKeys = () => Array.from(document.querySelectorAll("[data-dashboard-tab]"))
        .map((tab) => tab.dataset.dashboardTab)
        .filter(Boolean);

    const readModuleOrder = () => {
        try {
            const value = window.localStorage.getItem(moduleOrderKey);
            return value ? JSON.parse(value) : [];
        } catch (error) {
            return [];
        }
    };

    const writeModuleOrder = (order) => {
        try {
            window.localStorage.setItem(moduleOrderKey, JSON.stringify(order));
        } catch (error) {
            // Ignore storage failures.
        }
    };

    const normalizeModuleOrder = (order) => {
        const validKeys = getModuleKeys();
        const requested = Array.isArray(order) ? order : [];
        const normalized = requested.filter((key) => validKeys.includes(key));
        validKeys.forEach((key) => {
            if (!normalized.includes(key)) {
                normalized.push(key);
            }
        });
        return normalized;
    };

    const applyModuleOrder = (order) => {
        if (!tabsContainer) {
            return;
        }

        const normalized = normalizeModuleOrder(order);
        const tabMap = new Map(Array.from(document.querySelectorAll("[data-dashboard-tab]"))
            .map((tab) => [tab.dataset.dashboardTab, tab]));
        const panelMap = new Map(Array.from(document.querySelectorAll("[data-dashboard-panel]"))
            .map((panel) => [panel.dataset.dashboardPanel, panel]));
        const panelParent = panels.length ? panels[0].parentElement : null;

        normalized.forEach((key) => {
            const tab = tabMap.get(key);
            if (tab) {
                tabsContainer.appendChild(tab);
            }
            const panel = panelMap.get(key);
            if (panelParent && panel) {
                panelParent.appendChild(panel);
            }
        });
    };

    const persistCurrentOrder = () => {
        writeModuleOrder(getModuleKeys());
    };

    const setActive = (module) => {
        activeModule = module;
        tabs.forEach((tab) => {
            tab.classList.toggle("erp-tab--active", tab.dataset.dashboardTab === module);
        });

        panels.forEach((panel) => {
            panel.classList.toggle("hidden", panel.dataset.dashboardPanel !== module);
        });
    };

    const renderError = (panelBody, message) => {
        panelBody.innerHTML = `
            <div class="erp-empty">
                <div class="flex items-start gap-3">
                    <span class="erp-empty-icon">
                        <i data-lucide="triangle-alert" class="h-4 w-4"></i>
                    </span>
                    <div class="min-w-0 flex-1">
                        <h3 class="erp-empty-title">Dashboard module failed to load</h3>
                        <p class="erp-empty-message">${message}</p>
                    </div>
                </div>
            </div>
        `;
        updateIcons(panelBody);
    };

    const readCache = () => {
        try {
            return JSON.parse(window.sessionStorage.getItem(moduleCacheKey) || "{}");
        } catch (error) {
            return {};
        }
    };

    const writeCache = (cache) => {
        try {
            window.sessionStorage.setItem(moduleCacheKey, JSON.stringify(cache));
        } catch (error) {
            // Ignore storage failures.
        }
    };

    const getCachedModule = (module) => {
        const cache = readCache();
        const entry = cache[module];
        if (!entry || !entry.html || !entry.cachedAt) {
            return null;
        }
        if (Date.now() - entry.cachedAt > moduleCacheTtl) {
            delete cache[module];
            writeCache(cache);
            return null;
        }
        return entry.html;
    };

    const setCachedModule = (module, html) => {
        const cache = readCache();
        cache[module] = {
            html,
            cachedAt: Date.now(),
        };
        writeCache(cache);
    };

    const hydratePanel = (panelBody, module, html) => {
        panelBody.innerHTML = html || "";
        loaded.add(module);
        updateIcons(panelBody);
        if (typeof window.erpInitCharts === "function") {
            window.erpInitCharts(panelBody);
        }
    };

    const clearModuleCache = (module) => {
        const cache = readCache();
        delete cache[module];
        writeCache(cache);
        loaded.delete(module);
    };

    const loadModule = async (module, force = false) => {
        if (loaded.has(module) && !force) {
            return;
        }
        if (requests.has(module)) {
            return requests.get(module);
        }

        const panelBody = document.querySelector(`[data-dashboard-panel-body="${module}"]`);
        if (!panelBody) {
            return;
        }

        const cachedHtml = !force ? getCachedModule(module) : null;
        if (cachedHtml) {
            hydratePanel(panelBody, module, cachedHtml);
            return;
        }

        const request = fetch(`${moduleBaseUrl}/${module}`, {
            headers: {
                "X-Requested-With": "XMLHttpRequest",
            },
            credentials: "same-origin",
        })
            .then(async (response) => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                return response.json();
            })
            .then((payload) => {
                const html = payload.html || "";
                setCachedModule(module, html);
                hydratePanel(panelBody, module, html);
            })
            .catch((error) => {
                renderError(panelBody, error && error.message ? error.message : "Unexpected error");
            })
            .finally(() => {
                requests.delete(module);
            });

        requests.set(module, request);
        return request;
    };

    tabs.forEach((tab) => {
        tab.addEventListener("click", () => {
            const module = tab.dataset.dashboardTab;
            setActive(module);
            loadModule(module);
        });

        tab.addEventListener("dragstart", (event) => {
            draggedModule = tab.dataset.dashboardTab;
            tab.classList.add("opacity-70");
            if (event.dataTransfer) {
                event.dataTransfer.effectAllowed = "move";
                event.dataTransfer.setData("text/plain", draggedModule || "");
            }
        });

        tab.addEventListener("dragover", (event) => {
            event.preventDefault();
            if (!draggedModule || draggedModule === tab.dataset.dashboardTab) {
                return;
            }
            tab.classList.add("ring-1", "ring-primary/40");
            if (event.dataTransfer) {
                event.dataTransfer.dropEffect = "move";
            }
        });

        tab.addEventListener("dragleave", () => {
            tab.classList.remove("ring-1", "ring-primary/40");
        });

        tab.addEventListener("drop", (event) => {
            event.preventDefault();
            tab.classList.remove("ring-1", "ring-primary/40");
            const targetModule = tab.dataset.dashboardTab;
            if (!draggedModule || !targetModule || draggedModule === targetModule) {
                return;
            }

            const currentOrder = getModuleKeys();
            const fromIndex = currentOrder.indexOf(draggedModule);
            const toIndex = currentOrder.indexOf(targetModule);
            if (fromIndex === -1 || toIndex === -1) {
                return;
            }

            currentOrder.splice(fromIndex, 1);
            currentOrder.splice(toIndex, 0, draggedModule);
            applyModuleOrder(currentOrder);
            persistCurrentOrder();

            const reorderedModules = getModuleKeys();
            const firstModule = reorderedModules.length ? reorderedModules[0] : activeModule;
            if (draggedModule === firstModule) {
                setActive(draggedModule);
                loadModule(draggedModule);
            } else {
                setActive(activeModule);
            }
        });

        tab.addEventListener("dragend", () => {
            draggedModule = null;
            Array.from(document.querySelectorAll("[data-dashboard-tab]")).forEach((item) => {
                item.classList.remove("opacity-70", "ring-1", "ring-primary/40");
            });
        });
    });

    panelRefreshButtons.forEach((button) => {
        button.addEventListener("click", () => {
            const module = button.dataset.dashboardRefreshPanel;
            clearModuleCache(module);
            loadModule(module, true);
        });
    });

    if (refreshActiveButton) {
        refreshActiveButton.addEventListener("click", () => {
            clearModuleCache(activeModule);
            loadModule(activeModule, true);
        });
    }

    const initialPanelBody = document.querySelector(`[data-dashboard-panel-body="${initialModule}"]`);
    if (initialPanelBody && initialPanelBody.dataset.dashboardPrefilled === "1") {
        loaded.add(initialModule);
        setCachedModule(initialModule, initialPanelBody.innerHTML);
        updateIcons(initialPanelBody);
        if (typeof window.erpInitCharts === "function") {
            window.erpInitCharts(initialPanelBody);
        }
    }

    applyModuleOrder(readModuleOrder());
    persistCurrentOrder();

    const orderedModules = getModuleKeys();
    const bootModule = orderedModules.length ? orderedModules[0] : initialModule;

    setActive(bootModule);

    if (bootModule !== initialModule) {
        loadModule(bootModule);
    } else {
        loadModule(initialModule);
    }
    updateIcons(document);
});
</script>
