<div class="analyzer-root">

  <!-- Header -->
  <div class="analyzer-header">
    <mat-icon class="header-icon">analytics</mat-icon>
    <h2 class="header-title">Industrial Grading Studio</h2>
    <span class="mpob-badge">MPOB Standard</span>
  </div>

  <!-- Engine selector row -->
  <div class="engine-selector-row">
    <mat-form-field appearance="outline" class="engine-field">
      <mat-label>Inference Engine</mat-label>
      <mat-select [(ngModel)]="mode" [disabled]="loading$ | async" panelClass="engine-select-dropdown-panel">
        @for (opt of engineOptions; track opt.value) {
          <mat-option [value]="opt.value">
            <mat-icon>{{ opt.icon }}</mat-icon>
            {{ opt.label }}
          </mat-option>
        }
      </mat-select>
    </mat-form-field>

    <span class="engine-status-badge" [ngClass]="mode">
      @switch (mode) {
        @case ('local-onnx') { ONNX Runtime }
        @case ('local-tflite') { TFLite Runtime }
        @case ('remote') { Edge Server Active }
      }
    </span>
  </div>

  <!-- Input mode toggle -->
  <div class="input-mode-toggle">
    <button mat-flat-button [disabled]="loading$ | async" [class.active]="inputMode === 'file'" (click)="switchInputMode('file')">
      <mat-icon>upload_file</mat-icon>
      File Drop
    </button>
    <button mat-flat-button [disabled]="loading$ | async" [class.active]="inputMode === 'camera'" (click)="switchInputMode('camera')">
      <mat-icon>videocam</mat-icon>
      Live Camera
    </button>
  </div>

  <!-- File drop zone -->
  @if (inputMode === 'file') {
    <div
      class="drop-zone"
      [class.drag-over]="isDragOver"
      (dragover)="onDragOver($event)"
      (dragleave)="onDragLeave()"
      (drop)="onDrop($event)"
    >
      @if ((loading$ | async) && !isCameraActive) {
        <div class="loading-overlay">
          <mat-spinner diameter="52"></mat-spinner>
          <span class="loading-label">Analyzing batch&hellip;</span>
        </div>
      } @else {
        <mat-icon class="drop-icon">image_search</mat-icon>
        <p class="drop-primary">Drag &amp; drop images here</p>
        <p class="drop-secondary">or</p>
        <button mat-raised-button color="primary" type="button" [disabled]="loading$ | async" (click)="fileInput.click()">
          <mat-icon>upload_file</mat-icon>
          Select Images
        </button>
        <input
          #fileInput
          type="file"
          accept="image/*"
          multiple
          hidden
          (change)="onFileInput($event)"
        />
      }
    </div>
  }

  <!-- Live camera section -->
  @if (inputMode === 'camera') {
    <div class="camera-section">
      <video
        #videoEl
        autoplay
        playsinline
        class="camera-preview"
        [class.visible]="isCameraActive"
      ></video>

      @if ((loading$ | async) && isCameraActive) {
        <div class="camera-loading">
          <mat-spinner diameter="52"></mat-spinner>
          <span class="loading-label">Analyzing frame&hellip;</span>
        </div>
      }

      <div class="camera-controls">
        @if (!isCameraActive) {
          <button mat-raised-button color="primary" [disabled]="loading$ | async" (click)="startCamera()">
            <mat-icon>videocam</mat-icon>
            Start Camera
          </button>
        } @else {
          <button
            mat-raised-button
            color="accent"
            (click)="captureWebcamFrame()"
            [disabled]="(loading$ | async) === true"
          >
            <mat-icon>camera</mat-icon>
            Capture Frame
          </button>
          <button mat-stroked-button [disabled]="loading$ | async" (click)="stopCamera()">
            <mat-icon>videocam_off</mat-icon>
            Stop
          </button>
        }
      </div>
    </div>
  }

  <!-- Studio workspace: vertical stack -->
  <div class="studio-workspace">

    <!-- Canvas bounding box overlay (always in DOM so ViewChild resolves) -->
    <div class="canvas-container" [class.has-content]="!!currentFrame">
      <canvas #resultCanvas class="result-canvas"></canvas>
    </div>

    <!-- Batch carousel (visible when batch has multiple frames) -->
    @if (batchFrames.length > 1) {
      <div class="carousel-container">
        <button class="carousel-nav prev" (click)="prevFrame()">&#9664;</button>
        <div class="carousel-track">
          @for (frame of batchFrames; track frame.frameId; let i = $index) {
            <div class="carousel-card" [class.active]="i === selectedFrameIndex" (click)="selectFrame(i)">
              <span class="card-index">#{{ i + 1 }}</span>
              <span class="card-meta">{{ frame.detections.length }} det.</span>
            </div>
          }
        </div>
        <button class="carousel-nav next" (click)="nextFrame()">&#9654;</button>
      </div>
    }

    <!-- Detection results -->
    @if (currentFrame) {
      <div class="results-panel">

        <div class="results-header">
          <span class="results-title">
            Batch Result &mdash;
            <strong>{{ currentFrame.total_count }}</strong> detection(s)
          </span>
          <span class="timing-info">
            Inference: {{ currentFrame.inference_ms | number:'1.0-0' }}&nbsp;ms
            &nbsp;|&nbsp;
            Processing: {{ currentFrame.processing_ms | number:'1.0-0' }}&nbsp;ms
          </span>
        </div>

        <div class="results-body">
          <div class="detections-col">

            @if (currentFrame.detections.length) {
              @for (det of currentFrame.detections; track det.bunch_id) {
                <mat-card class="detection-card" [class.health-alert]="det.is_health_alert">
                  <mat-card-content>
                    <span
                      class="grade-dot"
                      [ngStyle]="{ background: gradeColor(det.class) }"
                    ></span>
                    <span class="grade-label">{{ det.class }}</span>
                    <span class="confidence-value">{{ confidencePercent(det.confidence) }}</span>
                    @if (det.is_health_alert) {
                      <mat-icon class="alert-icon" color="warn">warning</mat-icon>
                    }
                  </mat-card-content>
                </mat-card>
              }
            } @else {
              <p class="no-detections">No detections in this frame.</p>
            }

            @if (currentFrame.total_count > 0) {
              <div class="summary-block">
                <h4 class="summary-title">Industrial Summary</h4>
                <div class="summary-chips">
                  @for (entry of currentFrame.industrial_summary | keyvalue; track entry.key) {
                    <span
                      class="summary-chip"
                      [ngStyle]="{ 'border-color': gradeColor(entry.key) }"
                    >
                      {{ entry.key }}: <strong>{{ entry.value }}</strong>
                    </span>
                  }
                </div>
              </div>
            }

          </div>
        </div>
      </div>
    }

  </div>

</div>
