<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">
        @if (isLoading) {
        <div class="absolute inset-x-0 bottom-0">
            <mat-progress-bar [mode]="'indeterminate'"></mat-progress-bar>
        </div>
        }
        <div class="text-4xl font-extrabold tracking-tight">Category Management</div>
        <div class="mt-6 flex shrink-0 items-center sm:ml-4 sm:mt-0">
            <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 categories'" />
            </mat-form-field>
            <button class="ml-4" mat-flat-button [color]="'primary'" (click)="createCategory()">
                <mat-icon [svgIcon]="'heroicons_outline:plus'"></mat-icon>
                <span class="ml-2 mr-1">Add Category</span>
            </button>
        </div>
    </div>

    <!-- Main -->
    <div class="flex flex-auto overflow-hidden">
        <div class="flex flex-auto flex-col overflow-hidden sm:mb-18 sm:overflow-y-auto">
            @if (categories$ | async; as categories) {
            @if (categories.length > 0 || selectedCategory) {
            <div class="grid">
                <!-- Header -->
                <div class="category-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 [mat-sort-header]="'category_id'">Category ID</div>
                    <div [mat-sort-header]="'name'">Name</div>
                    <div class="hidden sm:block">Image</div>
                    <div class="hidden md:block" [mat-sort-header]="'brand_name'">Brand</div>
                    <div class="hidden lg:block" [mat-sort-header]="'branch_name'">Branch</div>
                    <!-- ⭐ NEW: Created By Column -->
                    <div class="hidden xl:block">Created By</div>
                    <div class="text-center">Actions</div>
                </div>

                <!-- New Category Form Row -->
                @if (selectedCategory && !selectedCategory.id) {
                <div class="category-grid grid items-center gap-4 border-b bg-blue-50 px-6 py-4 md:px-8">
                    <div class="truncate"><span class="text-xs font-medium text-blue-600">Auto-generated</span></div>
                    <div class="truncate font-medium text-blue-600">New Category</div>
                    <div class="hidden sm:block text-blue-600 text-sm">-</div>
                    <div class="hidden md:block text-blue-600 text-sm">-</div>
                    <div class="hidden 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>
                    <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>
                <div class="grid">
                    <ng-container
                        *ngTemplateOutlet="rowDetailsTemplate; context: { $implicit: selectedCategory }"></ng-container>
                </div>
                }

                <!-- Existing Categories -->
                @for (category of categories; track trackByFn($index, category)) {
                <div class="category-grid grid items-center gap-4 border-b px-6 py-4 hover:bg-gray-50 transition-colors md:px-8">
                    <div class="truncate">
                        <span class="text-xs font-mono text-blue-600 font-semibold">{{ category.category_id }}</span>
                    </div>
                    <div class="truncate">
                        <div class="font-semibold text-gray-900">{{ category.name }}</div>
                    </div>
                    <div class="hidden sm:flex items-center">
                        @if (category.image) {
                        <img [src]="getFullImageUrl(category.image)" [alt]="category.name"
                            class="h-10 w-10 rounded object-cover border">
                        } @else {
                        <div class="h-10 w-10 rounded bg-gray-100 flex items-center justify-center border">
                            <mat-icon class="icon-size-5 text-gray-400" [svgIcon]="'heroicons_outline:photo'"></mat-icon>
                        </div>
                        }
                    </div>
                    <div class="hidden md:block truncate">
                        <div class="text-sm text-gray-600">{{ category.brand_name }}</div>
                        <div class="text-xs text-gray-400">{{ category.brand_id }}</div>
                    </div>
                    <div class="hidden lg:block truncate">
                        <div class="text-sm text-gray-600">{{ category.branch_name }}</div>
                        <div class="text-xs text-gray-400">{{ category.branch_id }}</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>{{ category.created_by_username || 'N/A' }}</span>
                    </div>
                    <div class="flex items-center justify-center gap-1">
                        <button mat-icon-button (click)="toggleDetails(category.id)" 
                            [matTooltip]="selectedCategory?.id === category.id ? 'Hide Details' : 'View Details'">
                            <mat-icon class="icon-size-5 text-gray-600" [svgIcon]="
                                    selectedCategory?.id === category.id
                                        ? 'heroicons_outline:chevron-up'
                                        : 'heroicons_outline:chevron-down'
                                "></mat-icon>
                        </button>
                        <button mat-icon-button (click)="editCategory(category)" matTooltip="Edit">
                            <mat-icon class="icon-size-5 text-blue-600" [svgIcon]="'heroicons_outline:pencil'"></mat-icon>
                        </button>
                        <button mat-icon-button (click)="deleteCategory(category)" matTooltip="Delete">
                            <mat-icon class="icon-size-5 text-red-600" [svgIcon]="'heroicons_outline:trash'"></mat-icon>
                        </button>
                    </div>
                </div>

                @if (selectedCategory?.id === category.id) {
                <div class="grid">
                    <ng-container *ngTemplateOutlet="rowDetailsTemplate; context: { $implicit: category }"></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 {
            <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:squares-2x2'"></mat-icon>
                </div>
                <h3 class="text-2xl font-semibold text-gray-900 mb-2">No categories found</h3>
                <p class="text-sm text-gray-500 mb-6">Get started by creating your first category</p>
                <button mat-flat-button [color]="'primary'" (click)="createCategory()">
                    <mat-icon [svgIcon]="'heroicons_outline:plus'"></mat-icon>
                    <span class="ml-2">Add Category</span>
                </button>
            </div>
            }
            }

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

                                <!-- Form Fields -->
                                <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
                                    <!-- Category Name -->
                                    <mat-form-field class="w-full" appearance="outline">
                                        <mat-label>Category Name</mat-label>
                                        <input matInput [formControlName]="'name'" placeholder="e.g., Beverages" 
                                            (input)="onNameChange($event)" />
                                        <mat-error *ngIf="selectedCategoryForm.get('name')?.hasError('required')">
                                            Name is required
                                        </mat-error>
                                        <mat-hint>ID will be: {{ previewCategoryId }}</mat-hint>
                                    </mat-form-field>

                                    <!-- Branch Selection -->
                                    <mat-form-field class="w-full" appearance="outline">
                                        <mat-label>Branch</mat-label>
                                        <mat-select [formControlName]="'branch_id'" (selectionChange)="onBranchChange($event)">
                                            <mat-option *ngFor="let branch of branches" [value]="branch.branch_id">
                                                {{ branch.name }} ({{ branch.code }})
                                            </mat-option>
                                        </mat-select>
                                        <mat-error *ngIf="selectedCategoryForm.get('branch_id')?.hasError('required')">
                                            Branch is required
                                        </mat-error>
                                    </mat-form-field>

                                    <!-- Auto-filled Branch ID -->
                                    <mat-form-field class="w-full" appearance="outline">
                                        <mat-label>Branch ID</mat-label>
                                        <input matInput [value]="selectedBranchId" readonly />
                                        <mat-hint>Auto-filled from branch selection</mat-hint>
                                    </mat-form-field>

                                    <!-- Auto-filled Branch Name -->
                                    <mat-form-field class="w-full" appearance="outline">
                                        <mat-label>Branch Name</mat-label>
                                        <input matInput [value]="selectedBranchName" readonly />
                                        <mat-hint>Auto-filled from branch selection</mat-hint>
                                    </mat-form-field>

                                    <!-- Brand Selection (filtered by branch) -->
                                    <mat-form-field class="w-full" appearance="outline">
                                        <mat-label>Brand</mat-label>
                                        <mat-select [formControlName]="'brand_id'" (selectionChange)="onBrandChange($event)"
                                            [disabled]="!selectedBranchId">
                                            @if (!selectedBranchId) {
                                            <mat-option disabled>Select branch first</mat-option>
                                            }
                                            <mat-option *ngFor="let brand of filteredBrands" [value]="brand.brand_id">
                                                {{ brand.name }}
                                            </mat-option>
                                        </mat-select>
                                        <mat-error *ngIf="selectedCategoryForm.get('brand_id')?.hasError('required')">
                                            Brand is required
                                        </mat-error>
                                        <mat-hint>Brands filtered by selected branch</mat-hint>
                                    </mat-form-field>

                                    <!-- Auto-filled Brand ID -->
                                    <mat-form-field class="w-full" appearance="outline">
                                        <mat-label>Brand ID</mat-label>
                                        <input matInput [value]="selectedBrandId" readonly />
                                        <mat-hint>Auto-filled from brand selection</mat-hint>
                                    </mat-form-field>

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

                                    <!-- Category Image Upload -->
                                    <div class="md:col-span-2">
                                        <label class="block text-sm font-medium text-gray-700 mb-2">Category Image (Optional)</label>
                                        <div class="flex items-center gap-4">
                                            <div class="flex-shrink-0">
                                                @if (imagePreview || category.image) {
                                                <img [src]="imagePreview || getFullImageUrl(category.image)" [alt]="category.name"
                                                    class="h-24 w-24 rounded-lg object-cover border-2 border-gray-200">
                                                } @else {
                                                <div class="h-24 w-24 rounded-lg bg-gray-100 flex items-center justify-center border-2 border-dashed border-gray-300">
                                                    <mat-icon class="icon-size-8 text-gray-400" [svgIcon]="'heroicons_outline:photo'"></mat-icon>
                                                </div>
                                                }
                                            </div>
                                            <div class="flex-1">
                                                <label class="cursor-pointer inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                                                    <mat-icon class="icon-size-5 mr-2" [svgIcon]="'heroicons_outline:cloud-arrow-up'"></mat-icon>
                                                    Upload Image
                                                    <input type="file" accept="image/*" class="hidden" (change)="onImageSelected($event)">
                                                </label>
                                                <p class="mt-2 text-xs text-gray-500">PNG, JPG, GIF up to 5MB</p>
                                                @if (imagePreview || category.image) {
                                                <button type="button" mat-button color="warn" class="mt-2" (click)="removeImage()">
                                                    <mat-icon class="icon-size-5" [svgIcon]="'heroicons_outline:trash'"></mat-icon>
                                                    Remove Image
                                                </button>
                                                }
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                @if (category.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">{{ category.created_at | date:'medium' }}</span>
                                        </div>
                                        @if (category.updated_at && category.updated_at !== category.created_at) {
                                        <div>
                                            <span class="text-gray-500">Last Updated:</span>
                                            <span class="ml-2 text-gray-900">{{ category.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)="deleteSelectedCategory()"
                                    type="button" [disabled]="!category.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">{{ category.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)="updateSelectedCategory()"
                                        type="button" [disabled]="selectedCategoryForm.invalid || isLoading">
                                        @if (isLoading) {
                                        <mat-icon class="icon-size-5 animate-spin mr-2" [svgIcon]="'heroicons_outline:arrow-path'"></mat-icon>
                                        }
                                        <span>{{ category.id ? 'Update' : 'Create' }}</span>
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </ng-template>
        </div>
    </div>
</div>