@extends('layouts.user', ['heading' => 'Network Tree', 'subheading' => 'Genealogy, binary, and sponsor network view'])

@section('content')
    @php
        $baseQuery = request()->query();
    @endphp

    <div class="mb-4 grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
        <div class="user-card p-4">
            <div class="text-xs text-[var(--user-muted)]">Total Nodes (Loaded)</div>
            <div class="mt-1 text-xl font-semibold">{{ number_format((int) $treeStats['nodes']) }}</div>
            <div class="mt-1 text-xs text-[var(--user-muted)]">Depth {{ $depth }} limited lazy load</div>
        </div>
        <div class="user-card p-4">
            <div class="text-xs text-[var(--user-muted)]">Leg Strength</div>
            <div class="mt-1 text-sm font-semibold">Left: {{ number_format((int) $treeStats['left_nodes']) }}</div>
            <div class="text-sm font-semibold">Right: {{ number_format((int) $treeStats['right_nodes']) }}</div>
        </div>
        <div class="user-card p-4">
            <div class="text-xs text-[var(--user-muted)]">Binary Match Units</div>
            <div class="mt-1 text-xl font-semibold">{{ number_format((float) $binaryStats['match_units'], 2) }}</div>
            <div class="mt-1 text-xs text-[var(--user-muted)]">Weak Leg: {{ strtoupper($binaryStats['weak_leg']) }}</div>
        </div>
        <div class="user-card p-4">
            <div class="text-xs text-[var(--user-muted)]">Carry Forward</div>
            <div class="mt-1 text-sm font-semibold">L: {{ number_format((float) ($carry->repurchase_left ?? 0), 2) }}</div>
            <div class="text-sm font-semibold">R: {{ number_format((float) ($carry->repurchase_right ?? 0), 2) }}</div>
        </div>
    </div>

    <div class="user-card mb-4 p-4">
        <div class="mb-3 flex flex-wrap gap-2">
            <a href="{{ route('user.tree', array_merge($baseQuery, ['view' => 'genealogy'])) }}"
               class="rounded px-3 py-2 text-sm {{ $viewMode === 'genealogy' ? 'bg-[var(--user-primary)] text-white' : 'border border-[var(--user-border)] text-[var(--user-text)]' }}">
                Genealogy
            </a>
            <a href="{{ route('user.tree', array_merge($baseQuery, ['view' => 'binary'])) }}"
               class="rounded px-3 py-2 text-sm {{ $viewMode === 'binary' ? 'bg-[var(--user-primary)] text-white' : 'border border-[var(--user-border)] text-[var(--user-text)]' }}">
                Binary
            </a>
            <a href="{{ route('user.tree', array_merge($baseQuery, ['view' => 'sponsor'])) }}"
               class="rounded px-3 py-2 text-sm {{ $viewMode === 'sponsor' ? 'bg-[var(--user-primary)] text-white' : 'border border-[var(--user-border)] text-[var(--user-text)]' }}">
                Sponsor
            </a>
            <button type="button" data-tree-action="expand" class="rounded border border-[var(--user-border)] px-3 py-2 text-sm">Expand All</button>
            <button type="button" data-tree-action="collapse" class="rounded border border-[var(--user-border)] px-3 py-2 text-sm">Collapse All</button>
            <button type="button" data-tree-action="fit" class="rounded border border-[var(--user-border)] px-3 py-2 text-sm">Fit Screen</button>
            <button type="button" data-tree-action="fullscreen" class="rounded border border-[var(--user-border)] px-3 py-2 text-sm">Fullscreen</button>
            <button type="button" data-tree-action="zoom-in" class="rounded border border-[var(--user-border)] px-3 py-2 text-sm">Zoom +</button>
            <button type="button" data-tree-action="zoom-out" class="rounded border border-[var(--user-border)] px-3 py-2 text-sm">Zoom -</button>
        </div>

        <form method="GET" class="grid grid-cols-1 gap-2 md:grid-cols-5">
            <input type="hidden" name="view" value="{{ $viewMode }}">
            <input name="q" value="{{ $search }}" placeholder="Search ID, name, mobile, email"
                   class="rounded border border-[var(--user-border)] p-2 md:col-span-2" />
            <select name="status" class="rounded border border-[var(--user-border)] p-2">
                <option value="all" @selected($statusFilter === 'all')>All Status</option>
                <option value="active" @selected($statusFilter === 'active')>Active</option>
                <option value="pending" @selected($statusFilter === 'pending')>Pending</option>
                <option value="blocked" @selected($statusFilter === 'blocked')>Blocked</option>
            </select>
            <input type="number" min="1" max="8" name="depth" value="{{ $depth }}"
                   class="rounded border border-[var(--user-border)] p-2" />
            <button class="rounded bg-[var(--user-primary)] px-4 py-2 font-semibold text-white">Apply</button>
        </form>
    </div>

    <div class="grid grid-cols-1 gap-4 xl:grid-cols-3">
        <div class="user-card p-4 xl:col-span-2">
            <div class="mb-2 text-sm text-[var(--user-muted)]">
                Click any node for details. Tree loads depth-limited for large network performance.
            </div>
            <div id="treeViewport" class="max-h-[70vh] overflow-auto rounded-xl border border-[var(--user-border)] bg-slate-50 p-4">
                <div id="treeCanvas" class="origin-top-left min-w-[420px]"></div>
            </div>
        </div>

        <div class="user-card p-4">
            <div class="mb-2 text-sm font-semibold">Node Information</div>
            <div class="space-y-2 text-sm">
                <div><span class="text-[var(--user-muted)]">User ID:</span> <span id="info-member">{{ $focusNode['member_code'] ?? $user->member_code }}</span></div>
                <div><span class="text-[var(--user-muted)]">Name:</span> <span id="info-name">{{ $focusNode['name'] ?? $user->name }}</span></div>
                <div><span class="text-[var(--user-muted)]">Rank:</span> <span id="info-rank">{{ $focusNode['rank_name'] ?? 'Unranked' }}</span></div>
                <div><span class="text-[var(--user-muted)]">Status:</span> <span id="info-status">{{ ucfirst($focusNode['status'] ?? $user->status) }}</span></div>
                <div><span class="text-[var(--user-muted)]">Sponsor:</span> <span id="info-sponsor">{{ $focusNode['sponsor_code'] ?? '-' }}</span></div>
                <div><span class="text-[var(--user-muted)]">Join Date:</span> <span id="info-join">{{ $focusNode['joined_at'] ?? '-' }}</span></div>
                <div><span class="text-[var(--user-muted)]">Package:</span> <span id="info-package">{{ number_format((float) ($focusNode['package_amount'] ?? 0), 2) }}</span></div>
                <div><span class="text-[var(--user-muted)]">Personal BV:</span> <span id="info-pbv">{{ number_format((float) ($focusNode['personal_bv'] ?? 0), 2) }}</span></div>
                <div><span class="text-[var(--user-muted)]">Team Size:</span> <span id="info-team">{{ number_format((int) ($focusNode['team_size'] ?? 0)) }}</span></div>
                <div><span class="text-[var(--user-muted)]">Direct Referrals:</span> <span id="info-directs">{{ number_format((int) ($focusNode['direct_referrals'] ?? 0)) }}</span></div>
                <div><span class="text-[var(--user-muted)]">Income Wallet:</span> <span id="info-income">{{ number_format((float) ($focusNode['income_balance'] ?? 0), 2) }}</span></div>
            </div>
            <div class="mt-4 rounded-lg border border-[var(--user-border)] bg-white p-3 text-xs text-[var(--user-muted)]">
                Repurchase BV for rank:
                L {{ number_format((float) $binaryStats['left_repurchase_bv'], 2) }} /
                R {{ number_format((float) $binaryStats['right_repurchase_bv'], 2) }}
            </div>
        </div>
    </div>

    <script>
        (() => {
            const treeData = {
                rootId: {{ (int) $user->id }},
                focusId: {{ (int) ($focusNodeId ?? $user->id) }},
                mode: @json($viewMode),
                weakLeg: @json($binaryStats['weak_leg']),
                nodes: @json($nodes->values()),
                children: @json($childrenMap),
            };

            const canvas = document.getElementById('treeCanvas');
            const viewport = document.getElementById('treeViewport');
            if (!canvas || !viewport) return;

            const nodesById = new Map(treeData.nodes.map((node) => [Number(node.id), node]));
            const childrenByParent = treeData.children || {};
            let scale = 1;

            const escapeHtml = (value) => String(value ?? '')
                .replaceAll('&', '&amp;')
                .replaceAll('<', '&lt;')
                .replaceAll('>', '&gt;')
                .replaceAll('"', '&quot;')
                .replaceAll("'", '&#039;');

            const statusClass = (status) => {
                if (status === 'active') return 'bg-emerald-100 text-emerald-700';
                if (status === 'blocked') return 'bg-rose-100 text-rose-700';
                return 'bg-amber-100 text-amber-700';
            };

            const renderNode = (nodeId, depth = 0) => {
                const node = nodesById.get(Number(nodeId));
                if (!node) return '';

                const children = (childrenByParent[nodeId] || []).filter((childId) => nodesById.has(Number(childId)));
                const isFocus = Number(node.id) === Number(treeData.focusId);
                const weakLeg = treeData.mode !== 'sponsor' && node.top_leg === treeData.weakLeg;
                const cardClass = [
                    'rounded-xl border p-3 shadow-sm bg-white cursor-pointer',
                    weakLeg ? 'border-rose-300 bg-rose-50/40' : 'border-slate-200',
                    isFocus ? 'ring-2 ring-sky-400' : '',
                ].join(' ');

                const body = `
                    <div class="${cardClass}" data-node-id="${node.id}">
                        <div class="flex items-center justify-between gap-2">
                            <div class="text-sm font-semibold">${escapeHtml(node.member_code)} - ${escapeHtml(node.name)}</div>
                            <span class="rounded px-2 py-0.5 text-[11px] ${statusClass(node.status)}">${escapeHtml(String(node.status).toUpperCase())}</span>
                        </div>
                        <div class="mt-1 text-xs text-slate-600">
                            Rank: ${escapeHtml(node.rank_name || 'Unranked')} | Package: ${Number(node.package_amount || 0).toFixed(2)}
                        </div>
                        <div class="mt-1 text-xs text-slate-500">
                            Team: ${Number(node.team_size || 0)} | Direct: ${Number(node.direct_referrals || 0)}
                        </div>
                    </div>
                `;

                if (!children.length) {
                    return `<div class="mb-3">${body}</div>`;
                }

                const open = depth < 2 ? 'open' : '';
                const childHtml = children.map((childId) => renderNode(childId, depth + 1)).join('');

                return `
                    <details class="mb-3" ${open}>
                        <summary class="list-none [&::-webkit-details-marker]:hidden">${body}</summary>
                        <div class="ml-4 mt-2 border-l-2 border-slate-200 pl-4">${childHtml}</div>
                    </details>
                `;
            };

            const renderTree = () => {
                canvas.innerHTML = renderNode(treeData.rootId);
                bindNodeClicks();
                applyScale();
            };

            const setText = (id, value) => {
                const el = document.getElementById(id);
                if (el) el.textContent = value;
            };

            const bindNodeClicks = () => {
                canvas.querySelectorAll('[data-node-id]').forEach((el) => {
                    el.addEventListener('click', () => {
                        const node = nodesById.get(Number(el.getAttribute('data-node-id')));
                        if (!node) return;

                        treeData.focusId = Number(node.id);
                        setText('info-member', node.member_code || '-');
                        setText('info-name', node.name || '-');
                        setText('info-rank', node.rank_name || 'Unranked');
                        setText('info-status', String(node.status || '-').toUpperCase());
                        setText('info-sponsor', node.sponsor_code || '-');
                        setText('info-join', node.joined_at || node.created_at || '-');
                        setText('info-package', Number(node.package_amount || 0).toFixed(2));
                        setText('info-pbv', Number(node.personal_bv || 0).toFixed(2));
                        setText('info-team', Number(node.team_size || 0).toLocaleString());
                        setText('info-directs', Number(node.direct_referrals || 0).toLocaleString());
                        setText('info-income', Number(node.income_balance || 0).toFixed(2));
                        renderTree();
                    });
                });
            };

            const applyScale = () => {
                canvas.style.transform = `scale(${scale})`;
            };

            const toggleAll = (open) => {
                canvas.querySelectorAll('details').forEach((el) => {
                    el.open = open;
                });
            };

            document.querySelectorAll('[data-tree-action]').forEach((button) => {
                button.addEventListener('click', () => {
                    const action = button.getAttribute('data-tree-action');
                    if (action === 'expand') toggleAll(true);
                    if (action === 'collapse') toggleAll(false);
                    if (action === 'zoom-in') scale = Math.min(1.8, scale + 0.1);
                    if (action === 'zoom-out') scale = Math.max(0.55, scale - 0.1);
                    if (action === 'fit') scale = 1;
                    if (action === 'fullscreen') {
                        if (document.fullscreenElement) {
                            document.exitFullscreen();
                        } else {
                            viewport.requestFullscreen().catch(() => {});
                        }
                    }
                    applyScale();
                });
            });

            renderTree();
        })();
    </script>
@endsection
