<div class="bg-card flex min-w-0 flex-auto flex-col dark:bg-transparent sm:absolute sm:inset-0 sm:overflow-hidden">
    <!-- Header -->
    <div class="relative flex flex-0 flex-col border-b px-6 py-8 sm:flex-row sm:items-center sm:justify-between md:px-8">
        <!-- Loader -->
        @if (isLoading) {
        <div class="absolute inset-x-0 bottom-0">
            <mat-progress-bar [mode]="'indeterminate'"></mat-progress-bar>
        </div>
        }
        <!-- Title -->
        <div class="text-4xl font-extrabold tracking-tight">Branch Management</div>
        <!-- Actions -->
        <div class="mt-6 flex shrink-0 items-center sm:ml-4 sm:mt-0">
            <!-- Search -->
            <mat-form-field class="fuse-mat-dense fuse-mat-rounded min-w-64" [subscriptSizing]="'dynamic'">
                <mat-icon class="icon-size-5" matPrefix [svgIcon]="'heroicons_solid:magnifying-glass'"></mat-icon>
                <input matInput [formControl]="searchInputControl" [autocomplete]="'off'"
                    [placeholder]="'Search branches'" />
            </mat-form-field>
            <!-- Add branch button -->
            <button class="ml-4" mat-flat-button [color]="'primary'" (click)="createBranch()">
                <mat-icon [svgIcon]="'heroicons_outline:plus'"></mat-icon>
                <span class="ml-2 mr-1">Add Branch</span>
            </button>
        </div>
    </div>

    <!-- Main -->
    <div class="flex flex-auto overflow-hidden">
        <!-- Branches list -->
        <div class="flex flex-auto flex-col overflow-hidden sm:mb-18 sm:overflow-y-auto">
            @if (branches$ | async; as branches) {
            @if (branches.length > 0 || selectedBranch) {
            <div class="grid">
                <!-- Header -->
                <div class="branch-grid text-secondary sticky top-0 z-10 grid gap-4 bg-gray-50 px-6 py-4 text-sm font-semibold shadow dark:bg-black dark:bg-opacity-5 md:px-8"
                    matSort matSortDisableClear>
                    <div class="hidden md:block" [mat-sort-header]="'branch_id'">Branch ID</div>
                    <div [mat-sort-header]="'code'">Code</div>
                    <div [mat-sort-header]="'name'">Branch Name</div>
                    <div class="hidden lg:block" [mat-sort-header]="'location'">Location</div>
                    <div class="hidden lg:block" [mat-sort-header]="'contact'">Contact</div>
                    <!-- ⭐ NEW: Created By Column -->
                    <div class="hidden xl:block">Created By</div>
                    <div class="text-center">Actions</div>
                </div>

                <!-- New Branch Form Row -->
                @if (selectedBranch && !selectedBranch.id) {
                <div class="branch-grid grid items-center gap-4 border-b bg-blue-50 px-6 py-4 md:px-8">
                    <!-- Branch ID -->
                    <div class="hidden truncate md:block">
                        <span class="text-xs font-medium text-blue-600">Auto-generated</span>
                    </div>

                    <!-- Code -->
                    <div class="flex items-center">
                        <div class="truncate font-medium text-blue-600">New Branch</div>
                    </div>

                    <!-- Name -->
                    <div class="hidden truncate text-blue-600 text-sm">Creating...</div>

                    <!-- Location -->
                    <div class="hidden truncate lg:block text-blue-600 text-sm">-</div>

                    <!-- Contact -->
                    <div class="hidden truncate lg:block text-blue-600 text-sm">-</div>

                    <!-- ⭐ NEW: Created By (Auto) -->
                    <div class="hidden xl:block text-blue-600 flex items-center gap-1">
                        <mat-icon class="icon-size-4" [svgIcon]="'heroicons_outline:user'"></mat-icon>
                        <span>Auto</span>
                    </div>

                    <!-- Actions -->
                    <div class="flex items-center justify-center gap-2">
                        <button mat-icon-button (click)="closeDetails()" matTooltip="Close">
                            <mat-icon class="icon-size-5" [svgIcon]="'heroicons_outline:x-mark'"></mat-icon>
                        </button>
                    </div>
                </div>

                <!-- New Branch Form Details -->
                <div class="grid">
                    <ng-container
                        *ngTemplateOutlet="rowDetailsTemplate; context: { $implicit: selectedBranch }"></ng-container>
                </div>
                }

                <!-- Existing Branches -->
                @for (branch of branches; track trackByFn($index, branch)) {
                <div class="branch-grid grid items-center gap-4 border-b px-6 py-4 hover:bg-gray-50 transition-colors md:px-8">
                    <!-- Branch ID -->
                    <div class="hidden truncate md:block">
                        <span class="text-xs font-mono text-blue-600 font-semibold">{{ branch.branch_id }}</span>
                    </div>

                    <!-- Code -->
                    <div class="flex items-center">
                        <div class="truncate">
                            <div class="font-semibold text-gray-900">{{ branch.code }}</div>
                            <div class="text-xs text-gray-500 md:hidden">{{ branch.branch_id }}</div>
                        </div>
                    </div>

                    <!-- Name -->
                    <div class="truncate">
                        <div class="font-medium text-gray-900">{{ branch.name }}</div>
                    </div>

                    <!-- Location -->
                    <div class="hidden truncate lg:block">
                        <div class="text-sm text-gray-600">{{ branch.location }}</div>
                    </div>

                    <!-- Contact -->
                    <div class="hidden truncate lg:block">
                        <div class="text-sm text-gray-600">{{ branch.contact }}</div>
                    </div>

                    <!-- ⭐ NEW: Created By Column -->
                    <div class="hidden xl:block flex items-center gap-1">
                        <mat-icon class="icon-size-4 text-gray-500" [svgIcon]="'heroicons_outline:user'"></mat-icon>
                        <span>{{ branch.created_by_username || 'N/A' }}</span>
                    </div>

                    <!-- Actions -->
                    <div class="flex items-center justify-center gap-1">
                        <button mat-icon-button (click)="toggleDetails(branch.id)" 
                            [matTooltip]="selectedBranch?.id === branch.id ? 'Hide Details' : 'View Details'">
                            <mat-icon class="icon-size-5 text-gray-600" [svgIcon]="
                                    selectedBranch?.id === branch.id
                                        ? 'heroicons_outline:chevron-up'
                                        : 'heroicons_outline:chevron-down'
                                "></mat-icon>
                        </button>
                        <button mat-icon-button (click)="editBranch(branch)" matTooltip="Edit">
                            <mat-icon class="icon-size-5 text-blue-600" [svgIcon]="'heroicons_outline:pencil'"></mat-icon>
                        </button>
                        <button mat-icon-button (click)="deleteBranch(branch)" matTooltip="Delete">
                            <mat-icon class="icon-size-5 text-red-600" [svgIcon]="'heroicons_outline:trash'"></mat-icon>
                        </button>
                    </div>
                </div>

                <!-- Branch Details -->
                @if (selectedBranch?.id === branch.id) {
                <div class="grid">
                    <ng-container *ngTemplateOutlet="rowDetailsTemplate; context: { $implicit: branch }"></ng-container>
                </div>
                }
                }
            </div>

            <mat-paginator
                class="z-10 border-b bg-gray-50 dark:bg-transparent sm:absolute sm:inset-x-0 sm:bottom-0 sm:border-b-0 sm:border-t"
                [ngClass]="{ 'pointer-events-none': isLoading }" [length]="pagination.length"
                [pageIndex]="pagination.page" [pageSize]="pagination.size" [pageSizeOptions]="[5, 10, 25, 100]"
                [showFirstLastButtons]="true"></mat-paginator>
            } @else {
            <!-- Empty State -->
            <div class="flex flex-col items-center justify-center p-16">
                <div class="flex h-24 w-24 items-center justify-center rounded-full bg-gray-100 mb-6">
                    <mat-icon class="icon-size-16 text-gray-400" [svgIcon]="'heroicons_outline:building-office'"></mat-icon>
                </div>
                <h3 class="text-2xl font-semibold text-gray-900 mb-2">No branches found</h3>
                <p class="text-sm text-gray-500 mb-6">Get started by creating your first branch</p>
                <button mat-flat-button [color]="'primary'" (click)="createBranch()">
                    <mat-icon [svgIcon]="'heroicons_outline:plus'"></mat-icon>
                    <span class="ml-2">Add Branch</span>
                </button>
            </div>
            }
            }

            <!-- Row Details Template -->
            <ng-template #rowDetailsTemplate let-branch>
                <div class="overflow-hidden bg-white border-b">
                    <div class="flex">
                        <form class="flex w-full flex-col" [formGroup]="selectedBranchForm">
                            <div class="p-8">
                                <!-- Header -->
                                <div class="mb-6 pb-6 border-b">
                                    <h2 class="text-xl font-semibold text-gray-900">
                                        {{ branch.id ? 'Edit Branch' : 'Create New Branch' }}
                                    </h2>
                                    @if (branch.branch_id) {
                                    <p class="text-sm text-gray-500 mt-1">Branch ID: <span class="font-mono text-blue-600">{{ branch.branch_id }}</span></p>
                                    }
                                </div>

                                <!-- Form Fields -->
                                <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
                                    <!-- Branch Code -->
                                    <mat-form-field class="w-full" appearance="outline">
                                        <mat-label>Branch Code</mat-label>
                                        <input matInput [formControlName]="'code'" placeholder="e.g., BR001" />
                                        <mat-error *ngIf="selectedBranchForm.get('code')?.hasError('required')">
                                            Code is required
                                        </mat-error>
                                        <mat-error *ngIf="selectedBranchForm.get('code')?.hasError('pattern')">
                                            Use uppercase letters and numbers only
                                        </mat-error>
                                        <mat-hint>Unique branch identifier</mat-hint>
                                    </mat-form-field>

                                    <!-- Branch Name -->
                                    <mat-form-field class="w-full" appearance="outline">
                                        <mat-label>Branch Name</mat-label>
                                        <input matInput [formControlName]="'name'" placeholder="e.g., Main Branch" />
                                        <mat-error *ngIf="selectedBranchForm.get('name')?.hasError('required')">
                                            Name is required
                                        </mat-error>
                                        <mat-error *ngIf="selectedBranchForm.get('name')?.hasError('minlength')">
                                            Minimum 3 characters required
                                        </mat-error>
                                    </mat-form-field>

                                    <!-- Location -->
                                    <mat-form-field class="w-full" appearance="outline">
                                        <mat-label>Location</mat-label>
                                        <input matInput [formControlName]="'location'" placeholder="e.g., Mumbai" />
                                        <mat-error *ngIf="selectedBranchForm.get('location')?.hasError('required')">
                                            Location is required
                                        </mat-error>
                                    </mat-form-field>

                                    <!-- Contact -->
                                    <mat-form-field class="w-full" appearance="outline">
                                        <mat-label>Contact Number</mat-label>
                                        <input matInput type="tel" [formControlName]="'contact'" placeholder="9876543210" />
                                        <mat-error *ngIf="selectedBranchForm.get('contact')?.hasError('required')">
                                            Contact is required
                                        </mat-error>
                                        <mat-error *ngIf="selectedBranchForm.get('contact')?.hasError('pattern')">
                                            Enter valid 10-digit number
                                        </mat-error>
                                    </mat-form-field>

                                    <!-- Address - Full Width -->
                                    <mat-form-field class="w-full md:col-span-2" appearance="outline">
                                        <mat-label>Address</mat-label>
                                        <textarea matInput [formControlName]="'address'" rows="3"
                                            placeholder="Enter complete branch address"></textarea>
                                        <mat-error *ngIf="selectedBranchForm.get('address')?.hasError('required')">
                                            Address is required
                                        </mat-error>
                                        <mat-error *ngIf="selectedBranchForm.get('address')?.hasError('minlength')">
                                            Minimum 10 characters required
                                        </mat-error>
                                    </mat-form-field>

                                    <!-- ⭐ NEW: Created By Field (Read-only) -->
                                    @if (branch.id && branch.created_by_username) {
                                    <mat-form-field class="w-full" appearance="outline">
                                        <mat-label>Created By</mat-label>
                                        <input
                                            matInput
                                            [value]="branch.created_by_username"
                                            readonly
                                        />
                                        <mat-icon matPrefix class="icon-size-5" [svgIcon]="'heroicons_outline:user'"></mat-icon>
                                    </mat-form-field>
                                    }
                                </div>

                                <!-- Metadata -->
                                @if (branch.id) {
                                <div class="mt-6 pt-6 border-t">
                                    <div class="grid grid-cols-2 gap-4 text-sm">
                                        <div>
                                            <span class="text-gray-500">Created:</span>
                                            <span class="ml-2 text-gray-900">{{ branch.created_at | date:'medium' }}</span>
                                        </div>
                                        @if (branch.updated_at && branch.updated_at !== branch.created_at) {
                                        <div>
                                            <span class="text-gray-500">Last Updated:</span>
                                            <span class="ml-2 text-gray-900">{{ branch.updated_at | date:'medium' }}</span>
                                        </div>
                                        }
                                    </div>
                                </div>
                                }
                            </div>

                            <!-- Action Buttons -->
                            <div class="flex w-full items-center justify-between border-t bg-gray-50 px-8 py-4">
                                <button mat-button [color]="'warn'" (click)="deleteSelectedBranch()"
                                    type="button" [disabled]="!branch.id">
                                    Delete
                                </button>
                                <div class="flex items-center gap-3">
                                    @if (flashMessage) {
                                    <div class="flex items-center text-sm">
                                        @if (flashMessage === 'success') {
                                        <mat-icon class="icon-size-5 text-green-600 mr-2"
                                            [svgIcon]="'heroicons_outline:check-circle'"></mat-icon>
                                        <span class="text-green-600">{{ branch.id ? 'Updated' : 'Created' }} successfully</span>
                                        }
                                        @if (flashMessage === 'error') {
                                        <mat-icon class="icon-size-5 text-red-600 mr-2"
                                            [svgIcon]="'heroicons_outline:x-circle'"></mat-icon>
                                        <span class="text-red-600">Error occurred</span>
                                        }
                                    </div>
                                    }
                                    <button mat-stroked-button (click)="closeDetails()" type="button">
                                        Cancel
                                    </button>
                                    <button mat-flat-button [color]="'primary'" (click)="updateSelectedBranch()"
                                        type="button" [disabled]="selectedBranchForm.invalid || isLoading">
                                        @if (isLoading) {
                                        <mat-icon class="icon-size-5 animate-spin mr-2" [svgIcon]="'heroicons_outline:arrow-path'"></mat-icon>
                                        }
                                        <span>{{ branch.id ? 'Update' : 'Create' }}</span>
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </ng-template>
        </div>
    </div>
</div>