@extends('layouts.master')

@section('content')
<main>
    <!-- Left Sidebar -->
    <aside class="panel sidebar" id="left-panel">
        <div class="panel-header" onclick="toggleLeftPanel()" style="cursor:pointer">
            <h2>Category Explorer</h2>
            <i data-lucide="plus" size="14" style="color:var(--text-muted); cursor:pointer"></i>
        </div>
        <div style="padding: 10px 10px 0 10px; position: relative;">
            <input type="text" id="categorySearch" class="input" placeholder="Search categories..." onkeyup="searchCategories(this.value)" style="padding-right: 40px;">
            <span id="searchCount" style="position: absolute; right: 18px; top: 19px; font-size: 11px; background: #e2e8f0; color: #475569; padding: 2px 6px; border-radius: 10px; display: none; pointer-events: none; font-weight: 600;"></span>
        </div>
        <div id="tree"></div>
    </aside>
    <!-- Resizer Handle -->
    <div id="left-resizer" class="resizer-handle"></div>

    @if(auth()->user()->hasRole('admin'))
    <!-- Center Canvas -->
    <section class="diagram-container">
        <div class="diagram-viewer">
            <div class="diagram-scroller">
                <div id="diagram"></div>
            </div>
            
            <div class="canvas-controls">
                <div class="control-btn" id="zoom-out" title="Zoom Out"><i data-lucide="minus" size="14"></i></div>
                <div class="control-btn" id="zoom-in" title="Zoom In"><i data-lucide="plus" size="14"></i></div>
                <div style="width:1px; background:var(--border); margin:4px 0;"></div>
                <div class="control-btn" id="reset-zoom" title="Reset (100%)"><i data-lucide="maximize" size="16"></i></div>
                <span id="zoom-label" style="font-size: 11px; font-weight: 600; color: var(--text-muted); width: 40px; text-align: center;">100%</span>
            </div>
        </div>
    </section>
    @else
    <section style="flex:1; display:flex; align-items:center; justify-content:center; background:#f1f5f9; color:var(--text-muted);">
        <div style="text-align:center;">
            <i data-lucide="eye-off" size="48" style="margin-bottom:16px; opacity:0.5;"></i>
            <p>Diagram visualization is restricted to administrators.</p>
        </div>
    </section>
    @endif

    <!-- Right Sidebar -->
    <aside class="panel properties-panel properties" id="right-panel">
        <div class="panel-header" onclick="toggleRightPanel()" style="cursor:pointer">
            <h2>Node Properties</h2>
        </div>
        <div class="property-group">
            <!-- <div class="field">
                <label>Display Label</label>
                <input type="text" class="input" readonly placeholder="Selected Node">
            </div>
            <div class="field">
                <label>Description</label>
                <textarea class="textarea" readonly placeholder="Logic description area..."></textarea>
            </div>
            <div style="margin-top:auto; padding-top:16px; border-top:1px solid var(--border)">
                <p style="font-size:10px; color:var(--text-muted)">Changes are autosaved</p>
            </div> -->
            <div class="field">
            <label>Node Name</label>
<input type="text" class="input" id="nodeName">
</div>
<div class="field">
<label style="margin-top:10px;display:block;">Copy Into Parent</label>

<select id="copyTarget"></select>
</div>

<!-- <button class="btn-primary" style="margin-top:10px;width:100%" onclick="updateNode()">
Update Node
</button> -->
<!-- <button class="btn" style="margin-top:8px;width:100%" onclick="deleteNode()">
Delete Node
</button> -->

<button class="btn" style="margin-top:8px;width:100%" onclick="copySelectedNode()">
Copy Node
</button>

<div style="margin-top:20px; padding:20px; border-top:1px solid var(--border); background:#fff; border-radius:12px; border:1px solid var(--border); box-shadow:0 10px 25px rgba(0,0,0,0.02)">
    <label style="display:block; font-size:11px; font-weight:800; color:var(--text-muted); text-transform:uppercase; letter-spacing:0.05em; margin-bottom:12px;">Template Configuration</label>
    
    <div class="field" style="margin-bottom:16px;">
        <label>Template Name</label>
        <input type="text" class="input" id="templateName" value="{{ isset($template) ? collect(explode(' ', $template->name))->implode(' ') : '' }}" placeholder="Enter template name..." style="background:var(--bg-main); border-color:transparent;">
    </div>

    @if(isset($template))
        <input type="hidden" id="templateId" value="{{ $template->id }}">
        <div style="display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-top:10px;">
            <button class="btn" style="justify-content:center; height:42px; font-weight:600;" onclick="saveNewTemplate()">
                Save as New
            </button>
            <button class="btn btn-primary" onclick="updateTemplate()">
                Update Template
            </button>
        </div>
    @else
        <input type="hidden" id="templateId" value="">
        <button class="btn btn-primary"  onclick="saveNewTemplate()">
            Save Template
        </button>
    @endif
</div>
        </div>
    </aside>
</main>
@endsection

@push('styles')
<style>
    /* Panel Specific Layout */
    .node label.active{
        background:#e0edff;
    }
    .sidebar {
        width: var(--sidebar-width);
        border-right: 1px solid var(--border);
        position: relative;
    }
    
    /* Resizer Style */
    .resizer-handle {
        width: 4px;
        background: transparent;
        cursor: col-resize;
        transition: background 0.2s;
        z-index: 20;
        margin-left: -2px;
        margin-right: -2px;
    }
    .resizer-handle:hover, .resizer-handle.dragging {
        background: var(--text-muted);
    }
    .properties-panel {
        width: 260px;
        min-width: 260px;
        border-left: 1px solid var(--border);
    }

    #tree {
        flex: 1;
        overflow-y: auto;
        overflow-x: auto;
        padding: 10px;
    }

    .node {
        margin-bottom: 4px;
        white-space: nowrap;
        width: max-content;
        min-width: 100%;
    }

    .node label {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 6px 8px;
        border-radius: 4px;
        cursor: pointer;
        transition: background 0.2s;
    }
    
    .node label span {
        white-space: nowrap;
        overflow-x: auto;
        flex: 1;
        min-width: 0;
        display: block;
        padding-bottom: 2px;
    }

    .node label span::-webkit-scrollbar {
        height: 3px;
    }
    
    .node label span::-webkit-scrollbar-thumb {
        background: #cbd5e1;
        border-radius: 3px;
    }

    .node label:hover {
        background: var(--bg-main);
    }

    .children {
        margin-left: 14px;
        border-left: 1px dashed var(--border);
        padding-left: 10px;
        margin-top: 4px;
    }

    /* Diagram Area */
    .diagram-container {
        flex: 1;
        background: #f1f5f9;
        position: relative;
        overflow: hidden;
    }

    .diagram-viewer {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        flex-direction: column;
    }

    .diagram-scroller {
        flex: 1;
        overflow: auto;
        padding: 60px;
        position: relative;
    }

    #diagram {
        display: inline-block;
        background: transparent;
        transition: transform 0.2s ease-out;
        transform-origin: 0 0;
    }

    .canvas-controls {
        position: absolute;
        bottom: 24px;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        background: white;
        padding: 6px;
        border-radius: 10px;
        box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        border: 1px solid var(--border);
        gap: 6px;
        align-items: center;
        z-index: 1000;
    }

    .control-btn {
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 4px;
        cursor: pointer;
        color: var(--text-muted);
    }

    .control-btn:hover { background: var(--bg-main); color: var(--text-main); }

    .textarea { height: 100px; resize: none; }

    /* Custom Card Styles for Mermaid Nodes */
    /* Mermaid Node Box */
.mermaid .node rect{
    fill:#ffffff !important;
    stroke:#E5442A !important;
    stroke-width:1.5px !important;
    rx:6px !important;
    ry:6px !important;
}

/* Node text */
.mermaid .node text,
.mermaid .node .label,
.mermaid .node .label div,
.mermaid .node .label span {
    font-family: 'Inter', sans-serif !important;
    font-size: 14px !important;
    font-weight: 600 !important;
    fill: #0f172a !important;
    color: #0f172a !important;
    dominant-baseline: central !important;
}

/* Perfect center */
.mermaid svg text{
    text-anchor:middle !important;
    dominant-baseline:middle !important;
}

/* HTML labels center */
.mermaid .node .label div{
    text-align:center !important;
    padding:4px 8px !important;
    line-height:1.4 !important;
}
.mermaid svg text{
    text-anchor: middle !important;
}

/* .mermaid .nodeLabel{
    text-anchor: middle !important;
    dominant-baseline: middle !important;
} */
.mermaid .nodeLabel,
.mermaid .edgeLabel {
    color: #0f172a !important;
    text-align: center;
    font-family: 'Inter', sans-serif !important;
}

</style>
@endpush

@push('scripts')
<script>
    let selectedNode = null;
    let draggedNodeId = null;

function dragStart(e,id){
draggedNodeId=id;
}

function allowDrop(e){
e.preventDefault();
}
//     mermaid.initialize({
//     startOnLoad: false,
//     theme: "default",
//     flowchart: {
//         htmlLabels: true
//     }
// });

mermaid.initialize({
    startOnLoad:false,
    securityLevel:'loose',
    theme: "default",
    flowchart:{
        htmlLabels:false,
        useMaxWidth:false,
        curve: 'basis'
    },
    htmlLabels: true,
    themeVariables: {
        fontSize: '14px', 
        fontFamily: 'Inter',
        lineColor: '#E5442A',
        nodeBackground: '#ffffff',
        nodeBorder: '#E5442A',
        mainBkg: '#f8fafc',
        textColor: '#0f172a',
        nodeTextColor: '#0f172a',
        defaultColor: '#0f172a'
    }
});

let nodes = @json($diagram);
function getChildren(parent){
    return nodes.filter(n=>n.parent===parent);
}

/* INIT ROOT */
function init(){
    let root = getChildren(null);
    root.forEach(node=>{
        createNode(node,document.getElementById("tree"));
    });

    let isEditingTemplate = {{ isset($template) ? 'true' : 'false' }};
    let checkedCategories = @json($checkedCategories ?? []);

    if (isEditingTemplate) {
        function checkTemplateNodes(nodeList) {
            nodeList.forEach(node => {
                let isChecked = checkedCategories.includes(node.id);
                if (isChecked) {
                    let cb = document.querySelector(`input[data-id="${node.id}"]`);
                    if(cb && !cb.checked) {
                        cb.checked = true;
                    }
                }
                
                if (getChildren(node.id).length > 0) {
                    let expander = document.getElementById("expander_"+node.id);
                    if (expander && expander.innerText === '+') {
                        toggleExpand(node.id, expander, null);
                    }
                }
                checkTemplateNodes(getChildren(node.id));
            });
        }
        checkTemplateNodes(root);
        updateDiagram();
    } else {
        @if(auth()->check() && auth()->user()->hasRole('admin'))
        function checkAllNodes(nodeList) {
            nodeList.forEach(node => {
                if (getChildren(node.id).length > 0) {
                    let expander = document.getElementById("expander_"+node.id);
                    if (expander && expander.innerText === '+') {
                        toggleExpand(node.id, expander, null);
                    }
                }
                let cb = document.querySelector(`input[data-id="${node.id}"]`);
                if(cb && !cb.checked) {
                    cb.checked = true;
                }
                checkAllNodes(getChildren(node.id));
            });
        }
        checkAllNodes(root);
        updateDiagram();
        @endif
    }
}
function dropNode(e,parentId){

e.preventDefault();

if(!draggedNodeId || draggedNodeId==parentId) return;

let source = nodes.find(n=>n.id==draggedNodeId);

/* duplicate check */
let exist = nodes.find(n =>
n.parent==parentId &&
n.name.toLowerCase()==source.name.toLowerCase()
);

if(exist){
    customAlert("Child already exists under this parent");
    return;
}

/* API create */
apiFetch(`${baseUrl}/admin/categories`,{
method:'POST',
body:JSON.stringify({
name:source.name,
parent_id:parentId
})
})
.then(newNode=>{

newNode.parent=newNode.parent_id;
nodes.push(newNode);

appendChildren(parentId);

updateDiagram();

});

}
function toggleExpand(id, el, event) {
    if(event) {
        event.stopPropagation();
        event.preventDefault();
    }
    let parentDiv = document.getElementById("node_"+id);
    let childrenBox = parentDiv.querySelector(".children");
    
    if (el.innerText === '+') {
        el.innerText = '-';
        if (!childrenBox) {
            appendChildren(id);
        } else {
            childrenBox.style.display = 'block';
        }
    } else {
        el.innerText = '+';
        if (childrenBox) {
            childrenBox.style.display = 'none';
        }
    }
}

async function promptAddChild(parentId, event) {
    if (event) event.stopPropagation();
    
    let name = await showModal({
        title: 'Add Child Category',
        message: 'Enter the name for the new sub-category:',
        showInput: true,
        confirmText: 'Create Category'
    });

    if (!name) return;

    apiFetch(`${baseUrl}/admin/categories`, {
        method: 'POST',
        body: JSON.stringify({ name: name, parent_id: parentId })
    })
    .then(newNode => {
        newNode.parent = newNode.parent_id;
        nodes.push(newNode);

        /* Refresh children box */
        let parentDiv = document.getElementById("node_" + parentId);
        let childrenBox = parentDiv.querySelector(".children");
        if (childrenBox) {
            createNode(newNode, childrenBox);
        } else {
            appendChildren(parentId);
            let expander = document.getElementById("expander_" + parentId);
            if (expander) expander.innerText = '-';
        }
        
        updateDiagram();
        loadTree();
    })
    .catch(err => customAlert("Error adding category: " + err.message));
}

function createNode(node,container){
    let div=document.createElement("div");
    div.className="node";
    div.id="node_"+node.id;

    let hasChildren = getChildren(node.id).length > 0;
    let expandHtml = hasChildren ? `<span id="expander_${node.id}" onclick="toggleExpand(${node.id}, this, event)" style="cursor:pointer; width: 14px; height: 14px; display:inline-flex; align-items:center; justify-content:center; border:1px solid #94a3b8; border-radius:2px; font-size: 10px; font-weight:bold; margin-right:6px; background:#fff; line-height:1; user-select:none;">+</span>` : `<span style="width: 14px; margin-right:6px; display:inline-block;"></span>`;

div.innerHTML = `
<div style="display:flex; justify-content:space-between; align-items:center; width:100%; padding-right:8px;">
    <div style="display:flex; align-items:center; flex:1; min-width:0;">
        ${expandHtml}
        <label onclick="selectNode(${node.id})"
               draggable="true"
               ondragstart="dragStart(event,${node.id})"
               ondragover="allowDrop(event)"
               ondrop="dropNode(event,${node.id})"
               style="flex:1; display:flex; align-items:center; margin-bottom:0; cursor:pointer; min-width:0;">
            <input type="checkbox" data-id="${node.id}" onchange="toggleNode(this)">
            <span id="label_${node.id}" style="margin-left:4px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${node.name}</span>
        </label>
    </div>
    <div style="display:flex; align-items:center; gap:4px;">
        <div onclick="promptAddChild(${node.id}, event)" style="cursor:pointer; color:var(--primary); padding:2px 4px;" title="Add Child Category">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
        </div>
        <div onclick="promptDeleteNode(${node.id}, event)" style="cursor:pointer; color:#ef4444; padding:2px 4px;" title="Delete Category">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>
        </div>
    </div>
</div>
`;
    container.appendChild(div);
}

/* TOGGLE NODE */
function toggleNode(el){
    let id=parseInt(el.dataset.id);
    if(el.checked){
        appendChildren(id);
        let expander = document.getElementById("expander_"+id);
        if(expander) expander.innerText = '-';
        autoCheckParent(id);
    }else{
        removeChildren(id);
        let expander = document.getElementById("expander_"+id);
        if(expander) expander.innerText = '+';
    }
    updateDiagram();
}

/* APPEND CHILDREN */
function appendChildren(parentId){
    let parentDiv=document.getElementById("node_"+parentId);
    if(parentDiv.querySelector(".children")) return;

    let children=getChildren(parentId);
    if(!children.length) return;

    let box=document.createElement("div");
    box.className="children";

    children.forEach(child=>{
        createNode(child,box);
    });

    parentDiv.appendChild(box);
}

/* REMOVE CHILDREN */
function removeChildren(parentId){
    let parentDiv=document.getElementById("node_"+parentId);
    let childrenBox=parentDiv.querySelector(".children");
    if(childrenBox) childrenBox.remove();
}

/* AUTO SELECT PARENT */
function autoCheckParent(id){
    let node = nodes.find(n=>n.id===id);
    if(!node.parent) return;

    let parentCheckbox = document.querySelector(`input[data-id="${node.parent}"]`);
    if(parentCheckbox && !parentCheckbox.checked){
        parentCheckbox.checked=true;
        let expander = document.getElementById("expander_"+node.parent);
        if(expander && expander.innerText === '+') {
            toggleExpand(node.parent, expander, null);
        }
        autoCheckParent(node.parent); // recursive for multi-level
    }
}

/* BUILD DIAGRAM */
let zoomLevel = {{ (auth()->check() && auth()->user()->hasRole('admin')) ? '0.4' : '1.0' }};

function changeZoom(delta) {
    zoomLevel += delta;
    if (zoomLevel < 0.2) zoomLevel = 0.2;
    if (zoomLevel > 5.0) zoomLevel = 5.0; // Increased to 500%
    applyZoom();
}

function applyZoom() {
    const el = document.getElementById("diagram");
    const label = document.getElementById("zoom-label");
    if (el) {
        el.style.transform = `scale(${zoomLevel})`;
        // Origin is set in CSS as 0 0
    }
    if (label) {
        label.textContent = Math.round(zoomLevel * 100) + "%";
    }
}

// Setup CSRF for all AJAX calls
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;

function apiFetch(url, options = {}) {
    options.headers = {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': csrfToken,
        'Accept': 'application/json',
        ...options.headers
    };
    return fetch(url, options).then(async res => {
        if (!res.ok) {
            let errorMsg = 'API Error';
            try {
                let data = await res.json();
                if (data.message) errorMsg = data.message;
            } catch(e){}
            throw new Error(errorMsg);
        }
        return res.status === 204 ? null : res.json();
    });
}

// Bind zoom controls after DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('zoom-in').onclick = () => changeZoom(0.2);
    document.getElementById('zoom-out').onclick = () => changeZoom(-0.2);
    document.getElementById('reset-zoom').onclick = () => {
        zoomLevel = {{ (auth()->check() && auth()->user()->hasRole('admin')) ? '0.4' : '1.0' }};
        applyZoom();
    };
    applyZoom();
    initResizer();
});

function initResizer() {
    const resizer = document.getElementById('left-resizer');
    const panel = document.getElementById('left-panel');
    let isDragging = false;
    
    // Load saved width
    const savedWidth = localStorage.getItem('sidebar-width');
    if (savedWidth) {
        panel.style.width = savedWidth + 'px';
        panel.style.minWidth = savedWidth + 'px';
    }

    resizer.addEventListener('mousedown', (e) => {
        isDragging = true;
        resizer.classList.add('dragging');
        document.body.style.cursor = 'col-resize';
    });

    document.addEventListener('mousemove', (e) => {
        if (!isDragging) return;
        
        let newWidth = e.clientX; 
        
        // Boundaries
        if (newWidth < 200) newWidth = 200;
        if (newWidth > 800) newWidth = 800;
        
        panel.style.width = newWidth + 'px';
        panel.style.minWidth = newWidth + 'px';
        localStorage.setItem('sidebar-width', newWidth);
    });

    document.addEventListener('mouseup', () => {
        if (!isDragging) return;
        isDragging = false;
        resizer.classList.remove('dragging');
        document.body.style.cursor = 'default';
    });
}
function loadTree(){
    let select = $('#copyTarget');
    let options = "<option value=''>Select Parent</option>";

    nodes.forEach(n => {
        options += `<option value="${n.id}">${n.name}</option>`;
    });

    select.html(options).select2({
        width: '100%',
        placeholder: 'Search for parent...',
        dropdownParent: $('#right-panel')
    });
}
/* SELECT NODE */

function selectNode(id){

selectedNode=id;

document.querySelectorAll(".node label").forEach(l=>{
l.classList.remove("active");
});

let label=document.querySelector(`#node_${id} label`);

if(label) label.classList.add("active");

let node=nodes.find(n=>n.id==id);

document.getElementById("nodeName").value=node.name;

}
/* DELETE NODE */
function deleteNode(){
    if(!selectedNode){
        customAlert("Please select a category first.");
        return;
    }
    promptDeleteNode(selectedNode);
}

/* DELETE NODE WITH CONFIRMATION */
async function promptDeleteNode(id, event){
    if (event) {
        event.stopPropagation();
    }

    let confirmed = await showModal({
        title: 'Delete Category?',
        message: 'Are you sure you want to delete this category and all its children? This action cannot be undone.',
        type: 'danger',
        confirmText: 'Delete Permanently'
    });

    if(!confirmed) return;

    apiFetch(`${baseUrl}/admin/categories/${id}`, { method: 'DELETE' })
        .then(() => {
            /* remove node + children locally */
            nodes = nodes.filter(n => n.id != id && n.parent != id);
            
            /* remove UI */
            let div = document.getElementById("node_"+id);
            if(div) div.remove();

            if(selectedNode == id) {
                selectedNode = null;
                document.getElementById("nodeName").value="";
            }
            updateDiagram();
            loadTree();
        })
        .catch(err => customAlert("Error deleting category: " + err.message));
}
/* UPDATE NODE */

/* UPDATE NODE */
function updateNode(){
    if(!selectedNode){
        alert("Select node first");
        return;
    }

    let node = nodes.find(n => n.id == selectedNode);
    let newName = document.getElementById("nodeName").value;
    if(!newName) return;

    apiFetch(`${baseUrl}/categories/${selectedNode}`, {
        method: 'PUT',
        body: JSON.stringify({ name: newName, parent_id: node.parent })
    })
    .then(updatedNode => {
        node.name = updatedNode.name;
        
        /* sidebar label update */
        let label = document.getElementById("label_"+selectedNode);
        if(label) label.innerText = updatedNode.name;

        updateDiagram();
        loadTree();
        showModal({ title: 'Success', message: 'Category name updated successfully.', type: 'success', showCancel: false });
    })
    .catch(err => customAlert("Error updating category: " + err.message));
}
/* COPY NODE */

/* COPY/CREATE NODE */
function copySelectedNode(){
    if(!selectedNode){
        alert("Select node first");
        return;
    }

    let target = parseInt(document.getElementById("copyTarget").value);
    if(!target){
        alert("Select parent node");
        return;
    }

    let source = nodes.find(n => n.id == selectedNode);

    /* DUPLICATE CHECK */
    let alreadyExist = nodes.find(n =>
        n.parent == target &&
        n.name.toLowerCase() == source.name.toLowerCase()
    );

    apiFetch(`${baseUrl}/admin/categories`, {
        method: 'POST',
        body: JSON.stringify({ name: source.name, parent_id: target })
    })
    .then(newNode => {
        newNode.parent = newNode.parent_id; // Normalize for client logic
        nodes.push(newNode);

        /* APPEND UI */
        let parentDiv = document.getElementById("node_"+target);
        if(parentDiv){
            let childBox = parentDiv.querySelector(".children");
            if(!childBox){
                childBox = document.createElement("div");
                childBox.className="children";
                parentDiv.appendChild(childBox);
            }
            createNode(newNode, childBox);
        }
        updateDiagram();
        loadTree();
        showModal({ title: 'Success', message: 'Category copied successfully!', type: 'success', showCancel: false });
    })
    .catch(err => customAlert("Error copying category: " + err.message));
}

function saveNewTemplate() {
    let name = document.getElementById('templateName').value;
    if (!name) return customAlert('Please enter a template name');
    
    let checked = Array.from(document.querySelectorAll("input[type=checkbox]:checked")).map(c => parseInt(c.dataset.id));
    if (checked.length === 0) return customAlert('No categories selected. Please check at least one box to save a template.');

    apiFetch(`${baseUrl}/admin/templates`, {
        method: 'POST',
        body: JSON.stringify({ name: name, categories: checked })
    }).then(res => {
        showModal({ title: 'Success', message: 'Template saved successfully!', type: 'success', showCancel: false })
        .then(() => {
            window.location.href = `${baseUrl}/admin/templates`;
        });
    }).catch(err => customAlert(err.message));
}

function updateTemplate() {
    let id = document.getElementById('templateId').value;
    let name = document.getElementById('templateName').value;
    if (!name) return customAlert('Please enter a template name');

    let checked = Array.from(document.querySelectorAll("input[type=checkbox]:checked")).map(c => parseInt(c.dataset.id));
    if (checked.length === 0) return customAlert('No categories selected.');
    
    apiFetch(`${baseUrl}/admin/templates/${id}`, {
        method: 'PUT',
        body: JSON.stringify({ name: name, categories: checked })
    }).then(res => {
        showModal({ title: 'Success', message: 'Template updated successfully!', type: 'success', showCancel: false });
    }).catch(err => customAlert(err.message));
}

/* RENDER MERMAID */
function updateDiagram(){
    let checked = Array.from(document.querySelectorAll("input[type=checkbox]:checked"))
        .map(c=>parseInt(c.dataset.id));

    let text="flowchart LR\n";
    let edges=new Set();

    checked.forEach(id=>{
        let node = nodes.find(n=>n.id===id);
        if(node.parent){
            let parent = nodes.find(n=>n.id===node.parent);
            edges.add(`node${parent.id}["${parent.name}"] --> node${node.id}["${node.name}"]`);
        }
    });

    edges.forEach(e=>{
        text+=e+"\n";
    });

    const diagram=document.getElementById("diagram");
    diagram.innerHTML=`<div class="mermaid">${text}</div>`;

    mermaid.run({
        nodes:diagram.querySelectorAll('.mermaid')
    });
    setTimeout(()=>{

document.querySelectorAll(".mermaid .node").forEach(el=>{

let id=el.id.replace("node","");

el.onclick=function(){

document.querySelectorAll(".mermaid .node")
.forEach(n=>n.classList.remove("active-node"));

el.classList.add("active-node");

};

});

},200);
}
function searchCategories(query) {
    query = query.toLowerCase().trim();
    let countBadge = document.getElementById('searchCount');
    
    document.querySelectorAll(".node label span").forEach(span => {
        span.style.backgroundColor = 'transparent';
        span.style.color = '';
    });

    if (!query) {
        if(countBadge) countBadge.style.display = 'none';
        return;
    }

    let matches = nodes.filter(n => n.name.toLowerCase().includes(query));
    if(countBadge) {
        countBadge.innerText = matches.length;
        countBadge.style.display = 'block';
    }

    if (matches.length === 0) return;

    // Collapse all categories first
    document.querySelectorAll("[id^='expander_']").forEach(el => {
        if (el.innerText === '-') {
            el.innerText = '+';
            let id = el.id.replace("expander_", "");
            let parentDiv = document.getElementById("node_"+id);
            if(parentDiv){
                let childrenBox = parentDiv.querySelector(".children");
                if (childrenBox) childrenBox.style.display = 'none';
            }
        }
    });
    
    matches.forEach(match => {
        expandPathToNode(match.id);
        
        let labelSpan = document.getElementById("label_"+match.id);
        if (labelSpan) {
            labelSpan.style.backgroundColor = '#fef08a'; 
            labelSpan.style.color = '#854d0e'; 
            labelSpan.style.borderRadius = '4px';
        }
    });

    if (matches.length > 0) {
        let firstSpan = document.getElementById("label_" + matches[0].id);
        if (firstSpan) {
            firstSpan.scrollIntoView({ behavior: "smooth", block: "nearest" });
        }
    }
}

function expandPathToNode(id) {
    let node = nodes.find(n => n.id == id);
    if (!node || !node.parent) return;
    
    expandPathToNode(node.parent);
    
    let expander = document.getElementById("expander_"+node.parent);
    if (expander && expander.innerText === '+') {
        toggleExpand(node.parent, expander, null);
    }
}

init();
loadTree();
</script>
@endpush