@extends('layouts.master')

@section('content')
<main style="display: flex; height: calc(100vh - 60px);">
    @if(auth()->user()->hasRole('admin'))
    <section class="diagram-container" style="flex:1; background: #f1f5f9; position: relative; overflow: hidden;">
        <div style="position: absolute; top: 16px; left: 16px; z-index: 1000; background: white; padding: 16px; border-radius: 8px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); border: 1px solid var(--border);">
            <a href="{{ route('admin.templates.index') }}" class="btn" style="background:var(--bg-main); display:flex; align-items:center; gap:8px;">
                <i data-lucide="arrow-left" size="14"></i> Back to Templates
            </a>
            <h2 style="margin-top: 12px; margin-bottom: 0; font-size: 18px; color: var(--text-main); font-weight: 700;">{{ $template->name }}</h2>
        </div>
        
        <div class="diagram-viewer" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; display: flex; flex-direction: column;">
            <div class="diagram-scroller" style="flex: 1; overflow: auto; padding: 100px; position: relative;">
                <div id="diagram" style="display: inline-block; background: transparent; transition: transform 0.2s ease-out; transform-origin: 0 0;"></div>
            </div>
            
            <div class="canvas-controls" style="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;">
                <div class="control-btn" id="zoom-out" title="Zoom Out" style="width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; cursor: pointer; color: var(--text-muted);"><i data-lucide="minus" size="14" style="color: var(--text-muted);"></i></div>
                <div class="control-btn" id="zoom-in" title="Zoom In" style="width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; cursor: pointer; color: var(--text-muted);"><i data-lucide="plus" size="14" style="color: var(--text-muted);"></i></div>
                <div style="width:1px; background:var(--border); margin:4px 0; height: 16px;"></div>
                <div class="control-btn" id="reset-zoom" title="Reset (100%)" style="width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; cursor: pointer; color: var(--text-muted);"><i data-lucide="maximize" size="16" style="color: var(--text-muted);"></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; background: #f8fafc; padding: 40px; overflow-y: auto;">
        <div style="max-width: 800px; margin: 0 auto;">
            <a href="{{ route('admin.templates.index') }}" class="btn" style="margin-bottom: 24px;">
                <i data-lucide="arrow-left" size="14"></i> Back to Templates
            </a>
            <div class="panel" style="padding: 32px;">
                <h1 style="margin-top: 0;">{{ $template->name }}</h1>
                <p style="color: var(--text-muted);">Template created on {{ $template->created_at->format('M d, Y') }} by {{ $template->creator->name }}</p>
                
                <h3 style="margin-top: 32px; border-bottom: 1px solid var(--border); padding-bottom: 8px;">Selected Categories</h3>
                <div style="margin-top: 16px;">
                    @php
                        $selectedNodes = \App\Models\Category::whereIn('id', $checkedCategories)->get();
                    @endphp
                    <div style="display: flex; flex-wrap: wrap; gap: 8px;">
                        @foreach($selectedNodes as $node)
                            <span style="background: #e2e8f0; color: #475569; padding: 4px 12px; border-radius: 16px; font-size: 14px; font-weight: 500;">
                                {{ $node->name }}
                            </span>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
    </section>
    @endif
</main>
@endsection

@push('styles')
<style>
/* 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: 15px !important;
    font-weight: 700 !important;
    fill: #0f172a !important;
    color: #0f172a !important;
}

/* Long text override */
.mermaid .node.longText text,
.mermaid .node.longText .label,
.mermaid .node.longText .label div,
.mermaid .node.longText .label span {
    font-size: 12px !important;
}

/* HTML labels center */
.mermaid .node .label div{
    text-align:center !important;
    padding:4px 10px !important;
    line-height:1.4 !important;
    white-space: nowrap !important; /* Prevent truncation */
}

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

@push('scripts')
<script>
mermaid.initialize({
    startOnLoad:false,
    securityLevel:'loose',
    theme: "default",
    flowchart:{
        htmlLabels:true,
        useMaxWidth:false
    },
    htmlLabels: true,
    themeVariables: {
        fontSize: '15px', 
        fontFamily: 'Inter',
        lineColor: '#E5442A',
        nodeBackground: '#ffffff',
        nodeBorder: '#E5442A',
        mainBkg: '#ffffff',
        textColor: '#0f172a',
        nodeTextColor: '#0f172a',
        defaultColor: '#0f172a'
    }
});

let nodes = @json($diagram);
let checkedCategories = @json($checkedCategories ?? []);

let zoomLevel = {{ (auth()->check() && auth()->user()->hasRole('admin')) ? '0.8' : '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})`;
    }
    if (label) {
        label.textContent = Math.round(zoomLevel * 100) + "%";
    }
}

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.8' : '1.0' }};
        applyZoom();
    };
    applyZoom();
    renderDiagram();
});

function renderDiagram(){
    let text="flowchart LR\n";
    let edges=new Set();
    let nodesSet=new Set();

    checkedCategories.forEach(id=>{
        let node = nodes.find(n=>n.id===id);
        if(node && node.parent){
            let parent = nodes.find(n=>n.id===node.parent);
            if(parent) {
                edges.add(`node${parent.id}["${parent.name}"] --> node${node.id}["${node.name}"]`);
                nodesSet.add(parent);
                nodesSet.add(node);
            }
        } else if (node && !node.parent) {
            // Include root nodes even if they don't have children yet
            text += `node${node.id}["${node.name}"]\n`;
            nodesSet.add(node);
        }
    });

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

    // Apply classes based on length
    nodesSet.forEach(node => {
        if (node.name.length > 15) {
            text += `class node${node.id} longText\n`;
        }
    });

    text += "classDef longText font-size:12px,font-weight:700;\n";

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

    mermaid.run({
        nodes:document.querySelectorAll('.mermaid')
    });
}
</script>
@endpush
