@page "/raw"
@attribute [Authorize(Policy = AdminUiPolicies.ConfigEditor)]
@rendermode RenderMode.InteractiveServer
@using ZB.MOM.WW.OtOpcUa.AdminUI.Uns
@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Raw
@inject IRawTreeService Svc

@* Peer of GlobalUns (/uns) for the v3 Raw project tree — the cluster-rooted
   Enterprise → Cluster → Folder → Driver → Device → TagGroup → Tag hierarchy.
   Loads the eager roots on init, then hands off to RawTree, which lazily expands
   each container via IRawTreeService.LoadChildrenAsync and surfaces per-node
   context menus (real create/configure/tag modals arrive in later Batch-2 waves). *@

<PageTitle>Raw</PageTitle>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0">Raw</h4>
    <span class="text-muted small">Changes apply on the next deployment.</span>
</div>

<section class="panel rise" style="animation-delay:.02s">
    <div class="panel-head d-flex justify-content-between align-items-center flex-wrap gap-2">
        <span>Project tree</span>
    </div>

    @if (_loading)
    {
        <div style="padding:1rem" class="text-muted">
            <span class="spinner-border spinner-border-sm me-1"></span>Loading…
        </div>
    }
    else if (_loadError is not null)
    {
        <div style="padding:1rem" class="text-danger">@_loadError</div>
    }
    else if (_roots.Count == 0)
    {
        <div style="padding:1rem" class="text-muted">No clusters yet.</div>
    }
    else
    {
        <div style="padding:.5rem 1rem">
            <RawTree Roots="_roots" />
        </div>
    }
</section>

@code {
    private IReadOnlyList<RawNode> _roots = Array.Empty<RawNode>();
    private bool _loading = true;
    private string? _loadError;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            _roots = await Svc.LoadRootsAsync();
            // Auto-expand the Enterprise roots so the Cluster level (which owns the lazy plumbing) is
            // visible on load, mirroring GlobalUns.ExpandStructural. Enterprise children (clusters) are
            // eagerly materialised by LoadRootsAsync, so this needs no lazy fetch; clusters stay
            // collapsed and load their folders/drivers on first expand.
            foreach (var enterprise in _roots)
                enterprise.Expanded = true;
        }
        catch (Exception ex)
        {
            _loadError = $"Failed to load the Raw tree: {ex.Message}";
        }
        finally
        {
            _loading = false;
        }
    }
}
