@extends('layouts.app')

@section('title', __('New Inspection'))
@section('active', 'inspections')

@push('styles')
  <style>
    #dropZone.dragging { border-color: #4f6ef7; background: #eff3fe; transform: scale(1.005); }
    #dropZone { transition: all 0.25s ease; }
    .img-card:hover { transform: translateY(-2px); box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
    .img-card { transition: all 0.2s ease; }
    .img-card:hover .remove-btn { opacity: 1; }
    .remove-btn { opacity: 0; transition: opacity 0.2s; }
    #scanOverlay { display: none; }
    #scanOverlay.active { display: flex; }
    #successPanel { display: none; }
    #successPanel.active { display: block; animation: slideDown 0.4s ease; }
    #emptyState { display: none !important; }
  </style>
@endpush

@section('content')
  @php
    $statusClasses = [
      'completed' => 'bg-emerald-50 text-emerald-600',
      'review' => 'bg-amber-50 text-amber-600',
      'scanning' => 'bg-blue-50 text-blue-600',
      'scheduled' => 'bg-gray-100 text-gray-600',
    ];
    $severityClasses = [
      'high' => 'bg-red-50 text-red-600',
      'medium' => 'bg-amber-50 text-amber-600',
      'low' => 'bg-emerald-50 text-emerald-600',
    ];
  @endphp

  <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
    <div class="flex items-center gap-3">
      <a href="{{ route('dashboard') }}" class="h-9 w-9 rounded-xl flex items-center justify-center text-gray-500 hover:bg-gray-100 hover:text-gray-900 transition-colors">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>
      </a>
      <div>
        <h1 class="text-2xl font-bold tracking-tight">{{ __('New Inspection') }}</h1>
        <p class="text-sm text-gray-500">{{ __('Upload property images for AI-powered analysis') }}</p>
      </div>
    </div>
    <div id="headerBadges" class="hidden items-center gap-2">
      <div class="flex h-8 items-center gap-1.5 rounded-lg bg-[#eff3fe] px-3">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5 text-[#4f6ef7]" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
        <span id="imgCountBadge" class="text-xs font-medium text-[#4f6ef7]">0 images</span>
      </div>
      <div id="analysisReadyBadge" class="hidden h-8 items-center gap-1.5 rounded-lg bg-emerald-50 px-3">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5 text-emerald-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
        <span class="text-xs font-medium text-emerald-600">{{ __('Analysis ready') }}</span>
      </div>
    </div>
  </div>

  <div class="rounded-2xl border border-[#c7d3fc] bg-[#eff3fe] p-5 lg:p-6">
    <div class="mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
      <div>
        <p class="text-xs font-medium text-[#4f6ef7]">{{ __('Workspace') }}: {{ $activeWorkspace->name }}</p>
        <h2 class="mt-1 text-lg font-semibold">{{ __('Workspace / Collection') }}</h2>
      </div>
      <a href="{{ route('workspaces.index') }}" data-spa-link class="inline-flex items-center justify-center rounded-xl border border-[#c7d3fc] bg-white px-4 py-2 text-sm font-medium text-[#4f6ef7] hover:bg-[#f8faff]">{{ __('Manage Workspaces') }}</a>
    </div>
    <div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
      @foreach ($workspaces as $workspace)
        <a href="{{ route('inspections.index', ['workspace_id' => $workspace->id]) }}" data-spa-link class="rounded-xl border p-4 transition-colors {{ (int) $filters['workspace_id'] === $workspace->id ? 'border-[#4f6ef7] bg-white shadow-sm' : 'border-[#c7d3fc]/70 bg-white/60 hover:bg-white' }}">
          <div class="flex items-center justify-between gap-3">
            <p class="truncate text-sm font-semibold text-gray-900">{{ $workspace->name }}</p>
            <span class="rounded-full bg-[#eff3fe] px-2 py-0.5 text-[11px] font-medium text-[#4f6ef7]">{{ $workspace->collections_count }}</span>
          </div>
          <p class="mt-2 text-xs text-gray-500">{{ __('Total Inspections') }}</p>
          <p class="mt-1 text-lg font-bold">{{ $workspace->inspections_count }}</p>
          <p class="mt-1 text-xs text-gray-500">Rp {{ number_format($workspace->estimated_cost_sum ?? 0, 0, ',', '.') }}</p>
        </a>
      @endforeach
    </div>
  </div>

  <div id="successPanel" class="hidden rounded-2xl border border-emerald-200 bg-white shadow-lg overflow-hidden">
    <div class="relative bg-gradient-to-r from-emerald-50 via-emerald-50/60 to-[#eff3fe] px-6 py-5">
      <div class="flex items-center gap-3">
        <div class="scale-in flex h-12 w-12 items-center justify-center rounded-xl bg-emerald-500 shadow-md">
          <svg class="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
        </div>
        <div>
          <h3 class="text-lg font-semibold">{{ __('Analysis Complete!') }}</h3>
          <p id="successSubtitle" class="text-sm text-gray-500">{{ __('Images processed in 12s') }}</p>
        </div>
      </div>
    </div>
    <div class="p-6">
      <div class="mb-5 grid grid-cols-1 gap-3 sm:grid-cols-3">
        <div class="rounded-xl border border-gray-100 bg-white p-3 text-center shadow-sm">
          <p class="text-xs text-gray-400">{{ __('Damages') }}</p>
          <p class="text-2xl font-bold">{{ $stats['findings'] ?: 7 }}</p>
        </div>
        <div class="rounded-xl border border-gray-100 bg-white p-3 text-center shadow-sm">
          <p class="text-xs text-gray-400">{{ __('Confidence') }}</p>
          <p class="text-2xl font-bold text-[#4f6ef7]">96%</p>
        </div>
        <div class="rounded-xl border border-gray-100 bg-white p-3 text-center shadow-sm">
          <p class="text-xs text-gray-400">{{ __('Severity') }}</p>
          <p class="text-2xl font-bold text-amber-500">{{ __('Medium') }}</p>
        </div>
      </div>
      <div class="mb-5">
        <p class="mb-2 text-sm font-medium">{{ __('Damage Categories') }}</p>
        <div class="flex flex-wrap gap-2">
          <span class="text-xs font-medium bg-[#eff3fe] text-[#4f6ef7] border border-[#c7d3fc] px-2.5 py-1 rounded-full">Roof</span>
          <span class="text-xs font-medium bg-amber-50 text-amber-600 border border-amber-100 px-2.5 py-1 rounded-full">Moisture</span>
          <span class="text-xs font-medium bg-rose-50 text-rose-600 border border-rose-100 px-2.5 py-1 rounded-full">Electrical</span>
          <span class="text-xs font-medium bg-emerald-50 text-emerald-600 border border-emerald-100 px-2.5 py-1 rounded-full">Foundation</span>
          <span class="text-xs font-medium bg-gray-50 text-gray-600 border border-gray-100 px-2.5 py-1 rounded-full">HVAC</span>
          <span class="text-xs font-medium bg-gray-50 text-gray-600 border border-gray-100 px-2.5 py-1 rounded-full">Plumbing</span>
        </div>
      </div>
      <div id="roboflowResults" class="hidden mb-5 space-y-3"></div>
      <div class="flex flex-col gap-3 sm:flex-row sm:items-center">
        <a id="fullReportLink" href="{{ route('reports.index') }}" data-spa-link class="flex items-center gap-2 rounded-xl bg-[#4f6ef7] text-white px-4 py-2 text-sm font-medium shadow-sm hover:bg-[#3d5ce0] transition-colors">{{ __('View Full Report') }}</a>
        <button onclick="dismissResult()" class="rounded-xl border border-gray-200 bg-white text-gray-700 px-4 py-2 text-sm font-medium hover:bg-gray-50 transition-colors">{{ __('Dismiss') }}</button>
      </div>
    </div>
  </div>

  <div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
    <div class="lg:col-span-2 space-y-6">
      <div id="dropZone"
        ondragover="onDragOver(event)"
        ondragleave="onDragLeave(event)"
        ondrop="onDrop(event)"
        onclick="document.getElementById('fileInput').click()"
        class="group relative flex cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 hover:border-[#4f6ef7]/40 hover:bg-[#4f6ef7]/[0.02] transition-all duration-300 py-16">

        <input type="file" id="fileInput" accept="image/*" multiple class="hidden" onchange="onFileInput(event)">

        <div class="mb-4 flex h-16 w-16 items-center justify-center rounded-2xl bg-[#eff3fe] group-hover:scale-105 group-hover:bg-[#4f6ef7]/15 transition-all duration-300">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-[#4f6ef7]/70 group-hover:text-[#4f6ef7] group-hover:-translate-y-0.5 transition-all duration-300" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 16 12 12 8 16"/><line x1="12" y1="12" x2="12" y2="21"/><path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"/></svg>
        </div>

        <div id="dropTextEmpty">
          <h3 class="mb-1.5 text-lg font-semibold text-center">{{ __('Upload Property Images') }}</h3>
          <p class="mb-4 text-sm text-gray-500 text-center">{{ __('Drag & drop images here, or click to browse files') }}</p>
          <div class="flex justify-center">
            <button type="button" onclick="event.stopPropagation(); document.getElementById('fileInput').click()" class="flex items-center gap-2 rounded-xl bg-[#4f6ef7] text-white px-4 py-2 text-sm font-medium shadow-sm hover:bg-[#3d5ce0] transition-colors">{{ __('Select Images') }}</button>
          </div>
        </div>

        <div id="dropTextHasFiles" class="hidden text-center">
          <h3 id="dropTextTitle" class="mb-1 text-base font-semibold">0 images selected</h3>
          <p class="text-sm text-gray-500">{{ __('Click to add more images or drag & drop') }}</p>
        </div>

        <div class="mt-4 flex flex-wrap items-center justify-center gap-4 text-xs text-gray-400">
          <span>{{ __('JPG, PNG, WebP') }}</span>
          <span>{{ __('Max 10MB per image') }}</span>
          <span>{{ __('Up to 20 images') }}</span>
        </div>
      </div>

      <div id="previewSection" class="hidden space-y-4">
        <div class="flex items-center justify-between">
          <h3 class="text-sm font-medium">{{ __('Uploaded Images') }} (<span id="imgCountLabel">0</span>)</h3>
          <span id="uploadProgress" class="text-xs text-gray-400">0 of 0 uploaded</span>
        </div>
        <div id="imgGrid" class="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-3 xl:grid-cols-4"></div>
        <div class="rounded-2xl border border-gray-100 bg-white p-4 shadow-sm">
          <input id="priceResearchToggle" type="checkbox" class="hidden">
          <input id="sourceLinkModeSelect" type="hidden" value="both">
          <input id="laborDetailLevelSelect" type="hidden" value="detailed">
          <div class="mb-4 flex items-center justify-between">
            <div>
              <h3 class="text-sm font-semibold">{{ __('Analysis Options') }}</h3>
              <p class="text-xs text-gray-400">{{ __('Use the defaults for a quick report, or adjust only what you need.') }}</p>
            </div>
            <span id="modelCountLabel" class="rounded-full bg-gray-50 px-2.5 py-1 text-xs font-medium text-gray-500">{{ __('1 report') }}</span>
          </div>
          <div class="grid gap-4 lg:grid-cols-2">
            <div class="space-y-3">
              <div class="rounded-xl border border-[#c7d3fc] bg-[#eff3fe] p-3">
                <p class="mb-2 text-xs font-semibold uppercase tracking-wide text-[#4f6ef7]">{{ __('Workspace / Collection') }}</p>
                <div class="grid gap-3">
                  <label class="block">
                    <span class="mb-1 block text-xs font-medium text-gray-500">{{ __('Workspace') }}</span>
                    <select id="workspaceSelect" class="h-10 w-full rounded-xl border border-[#c7d3fc] bg-white px-3 text-sm outline-none focus:border-[#4f6ef7] focus:ring-2 focus:ring-[#4f6ef7]/20">
                      @foreach ($workspaces as $workspace)
                        <option value="{{ $workspace->id }}" @selected((int) $filters['workspace_id'] === $workspace->id)>{{ $workspace->name }} ({{ $workspace->collections_count }})</option>
                      @endforeach
                      <option value="__new">{{ __('Create new workspace') }}</option>
                    </select>
                  </label>
                  <label id="workspaceNameWrap" class="hidden">
                    <span class="mb-1 block text-xs font-medium text-gray-500">{{ __('New Workspace Name') }}</span>
                    <input id="workspaceNameInput" type="text" class="h-10 w-full rounded-xl border border-gray-200 bg-white px-3 text-sm outline-none focus:border-[#4f6ef7]" placeholder="{{ __('Example: Rumah Melati Renovation') }}">
                  </label>
                  <label class="block">
                    <span class="mb-1 block text-xs font-medium text-gray-500">{{ __('Existing Collection') }}</span>
                    <select id="collectionSelect" class="h-10 w-full rounded-xl border border-[#c7d3fc] bg-white px-3 text-sm outline-none focus:border-[#4f6ef7] focus:ring-2 focus:ring-[#4f6ef7]/20">
                      <option value="">{{ __('Create from fields below') }}</option>
                      @foreach ($collections as $collection)
                        <option value="{{ $collection->id }}" data-workspace-id="{{ $collection->inspection_workspace_id }}">{{ $collection->displayName() }} ({{ $collection->inspections_count }})</option>
                      @endforeach
                    </select>
                  </label>
                  <div class="grid gap-3 sm:grid-cols-2">
                    <label class="block">
                      <span class="mb-1 block text-xs font-medium text-gray-500">{{ __('House / Property') }}</span>
                      <input id="propertyNameInput" type="text" class="h-10 w-full rounded-xl border border-gray-200 bg-white px-3 text-sm outline-none focus:border-[#4f6ef7]" placeholder="{{ __('Example: Rumah Blok A') }}">
                    </label>
                    <label class="block">
                      <span class="mb-1 block text-xs font-medium text-gray-500">{{ __('Room / Area') }}</span>
                      <input id="roomNameInput" type="text" class="h-10 w-full rounded-xl border border-gray-200 bg-white px-3 text-sm outline-none focus:border-[#4f6ef7]" placeholder="{{ __('Example: Kamar Mandi 1') }}">
                    </label>
                  </div>
                  <label class="block">
                    <span class="mb-1 block text-xs font-medium text-gray-500">{{ __('Property Address') }}</span>
                    <input id="propertyAddressInput" type="text" class="h-10 w-full rounded-xl border border-gray-200 bg-white px-3 text-sm outline-none focus:border-[#4f6ef7]" placeholder="{{ __('Optional address') }}">
                  </label>
                </div>
              </div>
              <label class="block">
                <span class="mb-1 block text-xs font-medium text-gray-500">{{ __('Currency') }}</span>
                <select id="currencySelect" class="h-10 w-full rounded-xl border border-gray-200 bg-gray-50 px-3 text-sm outline-none focus:border-[#4f6ef7] focus:bg-white">
                  <option value="IDR">Rupiah (IDR)</option>
                  <option value="USD">US Dollar (USD)</option>
                </select>
              </label>
              <label class="block">
                <span class="mb-1 block text-xs font-medium text-gray-500">{{ __('Report Language') }}</span>
                <select id="outputLanguageSelect" class="h-10 w-full rounded-xl border border-gray-200 bg-gray-50 px-3 text-sm outline-none focus:border-[#4f6ef7] focus:bg-white">
                  <option value="id" @selected(app()->getLocale() === 'id')>{{ __('Indonesian') }}</option>
                  <option value="en" @selected(app()->getLocale() === 'en')>{{ __('English') }}</option>
                </select>
              </label>
              <div class="grid gap-3 sm:grid-cols-2">
                <label class="block">
                  <span class="mb-1 block text-xs font-medium text-gray-500">{{ __('Labor Pricing') }}</span>
                  <select id="laborPricingModeSelect" class="h-10 w-full rounded-xl border border-gray-200 bg-gray-50 px-3 text-sm outline-none focus:border-[#4f6ef7] focus:bg-white">
                    <option value="auto" selected>{{ __('Auto') }}</option>
                    <option value="daily">{{ __('Daily Rate') }}</option>
                    <option value="contract">{{ __('Contract/Borongan') }}</option>
                    <option value="monthly">{{ __('Monthly Crew') }}</option>
                  </select>
                </label>
              </div>
              <div class="rounded-xl border border-gray-100 bg-gray-50 p-3">
                <label class="flex items-center justify-between gap-3">
                  <span>
                    <span class="block text-sm font-medium text-gray-700">{{ __('Choose stores and handyman sources') }}</span>
                    <span class="text-xs text-gray-400">{{ __('Optional. Leave off to use the recommended defaults.') }}</span>
                  </span>
                  <input id="customSourcesToggle" type="checkbox" class="h-4 w-4 rounded border-gray-300 text-[#4f6ef7]">
                </label>
                <div id="customSourcesPanel" class="mt-3 hidden border-t border-gray-200 pt-3">
                  <p class="mb-2 text-xs font-medium text-gray-500">{{ __('Preferred Stores & Labor Sources') }}</p>
                  <div class="grid grid-cols-2 gap-2 text-sm">
                  <label class="flex items-center gap-2"><input type="checkbox" value="tokopedia" class="marketplace h-4 w-4 rounded border-gray-300 text-[#4f6ef7]" checked>Tokopedia</label>
                  <label class="flex items-center gap-2"><input type="checkbox" value="shopee" class="marketplace h-4 w-4 rounded border-gray-300 text-[#4f6ef7]" checked>Shopee</label>
                  <label class="flex items-center gap-2"><input type="checkbox" value="ace" class="marketplace h-4 w-4 rounded border-gray-300 text-[#4f6ef7]">ACE</label>
                  <label class="flex items-center gap-2"><input type="checkbox" value="depo_bangunan" class="marketplace h-4 w-4 rounded border-gray-300 text-[#4f6ef7]">Depo Bangunan</label>
                  <label class="flex items-center gap-2"><input type="checkbox" value="tukang_com" class="marketplace h-4 w-4 rounded border-gray-300 text-[#4f6ef7]" checked>Tukang.com</label>
                  <label class="flex items-center gap-2"><input type="checkbox" value="kanggo" class="marketplace h-4 w-4 rounded border-gray-300 text-[#4f6ef7]" checked>Kanggo</label>
                  <label class="flex items-center gap-2"><input type="checkbox" value="sejasa" class="marketplace h-4 w-4 rounded border-gray-300 text-[#4f6ef7]" checked>Sejasa</label>
                  <label class="flex items-center gap-2"><input type="checkbox" value="hwb" class="marketplace h-4 w-4 rounded border-gray-300 text-[#4f6ef7]" checked>HWB</label>
                  </div>
                  <label class="mt-3 flex items-center gap-2 text-sm">
                    <input id="includeServicesToggle" type="checkbox" class="h-4 w-4 rounded border-gray-300 text-[#4f6ef7]" checked>
                    {{ __('Include handyman recommendations') }}
                  </label>
                </div>
              </div>
              <div class="rounded-xl border border-gray-100 bg-gray-50 p-3">
                <label class="block">
                  <span class="mb-1 block text-sm font-medium text-gray-700">{{ __('Report Focus') }}</span>
                  <select id="reportFocusPreset" class="h-10 w-full rounded-xl border border-gray-200 bg-white px-3 text-sm outline-none focus:border-[#4f6ef7]">
                    <option value="complete" selected>{{ __('Complete inspection report') }}</option>
                    <option value="cost">{{ __('Cost and repair plan') }}</option>
                    <option value="safety">{{ __('Safety and urgency') }}</option>
                    <option value="maintenance">{{ __('Maintenance tips') }}</option>
                    <option value="custom">{{ __('Choose manually') }}</option>
                  </select>
                </label>
                <p id="reportFocusHelp" class="mt-2 text-xs leading-5 text-gray-400">{{ __('Covers damage, cost, labor, urgency, and safety.') }}</p>
                <div id="reportFocusCustomPanel" class="mt-3 hidden border-t border-gray-200 pt-3">
                  <p class="mb-2 text-xs font-medium text-gray-500">{{ __('Choose what the report should emphasize') }}</p>
                  <div class="grid grid-cols-1 gap-2 text-sm sm:grid-cols-2">
                    <label class="flex items-start gap-2 rounded-lg bg-white p-2"><input type="checkbox" value="materials" class="report-point mt-0.5 h-4 w-4 rounded border-gray-300 text-[#4f6ef7]" checked><span><span class="block font-medium text-gray-700">{{ __('Materials and items') }}</span><span class="text-xs text-gray-400">{{ __('What to buy for repairs') }}</span></span></label>
                    <label class="flex items-start gap-2 rounded-lg bg-white p-2"><input type="checkbox" value="labor" class="report-point mt-0.5 h-4 w-4 rounded border-gray-300 text-[#4f6ef7]" checked><span><span class="block font-medium text-gray-700">{{ __('Worker cost') }}</span><span class="text-xs text-gray-400">{{ __('Labor, duration, and roles') }}</span></span></label>
                    <label class="flex items-start gap-2 rounded-lg bg-white p-2"><input type="checkbox" value="urgency" class="report-point mt-0.5 h-4 w-4 rounded border-gray-300 text-[#4f6ef7]" checked><span><span class="block font-medium text-gray-700">{{ __('Repair priority') }}</span><span class="text-xs text-gray-400">{{ __('What should be fixed first') }}</span></span></label>
                    <label class="flex items-start gap-2 rounded-lg bg-white p-2"><input type="checkbox" value="safety" class="report-point mt-0.5 h-4 w-4 rounded border-gray-300 text-[#4f6ef7]" checked><span><span class="block font-medium text-gray-700">{{ __('Safety risk') }}</span><span class="text-xs text-gray-400">{{ __('Risks for occupants') }}</span></span></label>
                    <label class="flex items-start gap-2 rounded-lg bg-white p-2 sm:col-span-2"><input type="checkbox" value="preventive_maintenance" class="report-point mt-0.5 h-4 w-4 rounded border-gray-300 text-[#4f6ef7]"><span><span class="block font-medium text-gray-700">{{ __('Prevention tips') }}</span><span class="text-xs text-gray-400">{{ __('How to avoid repeated damage') }}</span></span></label>
                  </div>
                </div>
              </div>
            </div>
            <div class="space-y-3">
              <div>
                <p class="text-xs font-medium text-gray-500">{{ __('Roboflow Detection Model') }}</p>
                <p class="mt-1 text-xs leading-5 text-gray-400">{{ __('Choose the first-stage detector before AI report analysis.') }}</p>
              </div>
              <div class="grid gap-2">
                <label class="roboflow-model-card flex cursor-pointer items-start gap-3 rounded-xl border border-[#c7d3fc] bg-[#eff3fe] p-3">
                  <input type="radio" name="roboflow_model" value="modelv1-low" class="roboflow-model mt-1 h-4 w-4 border-gray-300 text-[#4f6ef7]" checked>
                  <span><span class="block text-sm font-semibold text-gray-800">{{ __('Model v1 - accurate filter') }}</span><span class="text-xs text-gray-500">{{ __('Slower, but better for filtering real home damage.') }}</span></span>
                </label>
                <label class="roboflow-model-card flex cursor-pointer items-start gap-3 rounded-xl border border-gray-100 bg-gray-50 p-3">
                  <input type="radio" name="roboflow_model" value="modelv2-accurate" class="roboflow-model mt-1 h-4 w-4 border-gray-300 text-[#4f6ef7]">
                  <span><span class="block text-sm font-semibold text-gray-800">{{ __('Model v2 - fast experimental') }}</span><span class="text-xs text-gray-500">{{ __('Faster, but less stable; suspicious detections are filtered harder.') }}</span></span>
                </label>
              </div>
            </div>
            <div class="space-y-3">
              <div class="rounded-xl border border-gray-100 bg-gray-50 p-3">
                <div class="flex items-start justify-between gap-3">
                  <div>
                    <p class="text-xs font-medium text-gray-500">{{ __('Scan Mode') }}</p>
                    <p id="scanModeHelp" class="mt-1 text-xs leading-5 text-gray-400">{{ __('Good for quick checks and small repairs.') }}</p>
                  </div>
                </div>
                <div class="mt-3 grid grid-cols-3 gap-1 rounded-xl bg-white p-1">
                  <label class="scan-mode-card flex h-9 cursor-pointer items-center justify-center rounded-lg border border-[#c7d3fc] bg-[#eff3fe] px-2 text-center text-xs font-semibold text-[#4f6ef7]">
                    <input type="radio" name="scan_mode" value="quick" class="scan-mode sr-only" checked>
                    {{ __('Fast') }}
                  </label>
                  <label class="scan-mode-card flex h-9 cursor-pointer items-center justify-center rounded-lg border border-transparent bg-transparent px-2 text-center text-xs font-semibold text-gray-500">
                    <input type="radio" name="scan_mode" value="detail" class="scan-mode sr-only">
                    {{ __('Detail') }}
                  </label>
                  <label class="scan-mode-card flex h-9 cursor-pointer items-center justify-center rounded-lg border border-transparent bg-transparent px-2 text-center text-xs font-semibold text-gray-500">
                    <input type="radio" name="scan_mode" value="deep" class="scan-mode sr-only">
                    {{ __('Deep') }}
                  </label>
                </div>
              </div>
            </div>
          </div>
          <div class="mt-4 rounded-xl border border-gray-100 bg-gray-50 p-3">
            <label class="flex items-center justify-between gap-3">
              <span>
                <span class="block text-sm font-medium text-gray-700">{{ __('Expert settings') }}</span>
                <span class="text-xs text-gray-400">{{ __('Usually safe to leave unchanged.') }}</span>
              </span>
              <input id="expertSettingsToggle" type="checkbox" class="h-4 w-4 rounded border-gray-300 text-[#4f6ef7]">
            </label>
            <div id="expertSettingsPanel" class="mt-3 hidden grid gap-4 border-t border-gray-200 pt-3 sm:grid-cols-2">
              <label>
                <span class="mb-1 block text-xs font-medium text-gray-500">{{ __('Creativity') }}</span>
                <input id="temperatureInput" type="range" min="0" max="1" step="0.1" value="0" class="w-full accent-[#4f6ef7]">
              </label>
              <label>
                <span class="mb-1 block text-xs font-medium text-gray-500">{{ __('Report length limit') }}</span>
                <input id="maxTokensInput" type="number" min="512" max="4096" step="256" value="2048" class="h-10 w-full rounded-xl border border-gray-200 bg-white px-3 text-sm outline-none focus:border-[#4f6ef7]">
              </label>
            </div>
          </div>
        </div>
        <div id="analyzeWrap" class="hidden flex items-center justify-center pt-2">
          <button id="analyzeBtn" type="button" onclick="startAnalysis()" class="flex items-center gap-2 rounded-xl bg-[#4f6ef7] px-8 py-3 text-base font-semibold text-white shadow-md hover:bg-[#3d5ce0] hover:shadow-lg transition-all duration-200">
            {{ __('Analyze with AI') }}
          </button>
        </div>
      </div>

      <div id="emptyState" class="hidden">
        <div class="relative mb-6">
          <div class="flex h-24 w-24 items-center justify-center rounded-3xl bg-gradient-to-br from-[#4f6ef7]/10 to-[#4f6ef7]/5">
            <div class="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-[#4f6ef7]/15 to-[#4f6ef7]/5">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-[#4f6ef7]/60" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
            </div>
          </div>
        </div>
        <h3 class="mb-2 text-lg font-semibold">{{ __('Start Your Inspection') }}</h3>
        <p class="mb-6 max-w-sm text-sm text-gray-500 leading-relaxed">{{ __('Upload property images to begin AI-powered analysis. The system will detect damages, assess conditions, and generate report-ready findings.') }}</p>
        <div class="grid grid-cols-1 gap-3 sm:grid-cols-3 w-full max-w-lg">
          <div class="flex flex-col items-center gap-2 rounded-xl border border-gray-100 bg-white p-4 shadow-sm"><p class="text-xs font-medium">{{ __('Upload') }}</p><p class="text-[10px] text-gray-400">{{ __('Drag or select images') }}</p></div>
          <div class="flex flex-col items-center gap-2 rounded-xl border border-gray-100 bg-white p-4 shadow-sm"><p class="text-xs font-medium">{{ __('Preview') }}</p><p class="text-[10px] text-gray-400">{{ __('Review before analysis') }}</p></div>
          <div class="flex flex-col items-center gap-2 rounded-xl border border-gray-100 bg-white p-4 shadow-sm"><p class="text-xs font-medium">{{ __('Analyze') }}</p><p class="text-[10px] text-gray-400">{{ __('AI scans for damage') }}</p></div>
        </div>
      </div>
    </div>

    <div class="space-y-6">
      <div class="rounded-2xl border border-gray-100 bg-white shadow-sm overflow-hidden">
        <div class="relative bg-gradient-to-br from-[#eff3fe] via-[#e8eefe] to-[#eff3fe] px-6 py-5">
          <div class="relative flex items-start gap-3">
            <div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-[#4f6ef7] text-white">
              AI
            </div>
            <div>
              <p class="text-base font-semibold">{{ __('AI Analysis Engine') }}</p>
              <p class="mt-0.5 text-sm text-gray-500">{{ __('Powered by InspectAI v2.4') }}</p>
            </div>
          </div>
          <div class="mt-3 flex items-center gap-1.5">
            <span class="h-2 w-2 rounded-full bg-[#4f6ef7] pulse-dot"></span>
            <span class="text-xs text-gray-500">{{ __('Processing time: ~30 seconds per image') }}</span>
          </div>
        </div>
        <div class="p-4 space-y-1">
          <div class="group flex items-start gap-3 rounded-xl p-2.5 hover:bg-gray-50 transition-colors">
            <div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[#eff3fe] text-[#4f6ef7]">1</div>
            <div><p class="text-sm font-medium">{{ __('Damage Detection') }}</p><p class="text-xs text-gray-400 leading-relaxed">{{ __('Identifies structural damage, water leaks, cracks, and deterioration.') }}</p></div>
          </div>
          <div class="group flex items-start gap-3 rounded-xl p-2.5 hover:bg-gray-50 transition-colors">
            <div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[#eff3fe] text-[#4f6ef7]">2</div>
            <div><p class="text-sm font-medium">{{ __('Safety Assessment') }}</p><p class="text-xs text-gray-400 leading-relaxed">{{ __('Evaluates hazards and structural integrity concerns.') }}</p></div>
          </div>
          <div class="group flex items-start gap-3 rounded-xl p-2.5 hover:bg-gray-50 transition-colors">
            <div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[#eff3fe] text-[#4f6ef7]">3</div>
            <div><p class="text-sm font-medium">{{ __('Cost Estimation') }}</p><p class="text-xs text-gray-400 leading-relaxed">{{ __('Provides repair cost estimates based on severity.') }}</p></div>
          </div>
        </div>
      </div>

      <div class="rounded-2xl border border-gray-100 bg-white shadow-sm">
        <div class="px-5 pt-5 pb-3">
          <h3 class="text-base font-semibold">{{ __('Recent Uploads') }}</h3>
          <p class="text-sm text-gray-400 mt-0.5">{{ __('Latest dynamic property inspections') }}</p>
        </div>
        <div class="px-4 pb-5 overflow-y-auto max-h-[370px] space-y-2">
          @forelse ($inspections->take(4) as $inspection)
            @php
              $recentImages = collect($inspection->source_image_paths ?? [])
                ->merge($inspection->visualization_image_paths ?? [])
                ->filter(fn ($image) => is_array($image) && filled($image['url'] ?? null))
                ->unique(fn ($image) => $image['url'])
                ->take(4)
                ->values();
            @endphp
            <div class="flex items-start gap-3 rounded-xl border border-transparent p-3 hover:border-gray-100 hover:bg-gray-50/50 transition-all">
              @if ($recentImages->isNotEmpty())
                <div class="grid h-14 w-14 shrink-0 grid-cols-2 gap-0.5 overflow-hidden rounded-xl bg-gray-950 ring-1 ring-gray-100">
                  @foreach ($recentImages as $image)
                    @php
                      $imageLabel = $image['name'] ?? $image['key'] ?? $inspection->property_name;
                    @endphp
                    <button type="button" onclick="openScanImageModal('{{ e($image['url']) }}', '{{ e($imageLabel) }}')" class="group/thumb overflow-hidden bg-gray-900">
                      <img src="{{ $image['url'] }}" alt="{{ $imageLabel }}" class="h-full w-full object-cover transition-transform duration-200 group-hover/thumb:scale-110" loading="lazy">
                    </button>
                  @endforeach
                  @for ($slot = $recentImages->count(); $slot < 4; $slot++)
                    <div class="bg-gray-900"></div>
                  @endfor
                </div>
              @else
                <div class="flex h-14 w-14 shrink-0 items-center justify-center rounded-xl bg-gray-100 text-gray-400">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                </div>
              @endif
              <div class="flex-1 min-w-0">
                <p class="truncate text-sm font-medium">{{ $inspection->property_name }}</p>
                <div class="mt-0.5 flex items-center gap-3 text-xs text-gray-400">
                  <span>{{ $inspection->scheduled_at?->format('M d, Y') ?? '-' }}</span>
                  <span>{{ $inspection->damage_findings_count }} findings</span>
                </div>
                <div class="mt-1.5 flex items-center gap-2">
                  <span class="text-[10px] font-medium px-1.5 py-0.5 rounded-full {{ $statusClasses[$inspection->status] ?? 'bg-gray-100 text-gray-600' }}">{{ Str::headline($inspection->status) }}</span>
                  <span class="text-xs font-medium text-amber-500">{{ $inspection->estimated_cost_label ?? 'Rp '.number_format($inspection->estimated_cost, 0, ',', '.') }}</span>
                </div>
              </div>
            </div>
          @empty
            <p class="px-3 py-8 text-center text-sm text-gray-400">{{ __('No inspections yet.') }}</p>
          @endforelse
        </div>
      </div>

      <div class="rounded-2xl border border-gray-100 bg-white shadow-sm">
        <div class="px-5 pt-5 pb-3">
          <h3 class="text-base font-semibold">{{ __('Recent Findings') }}</h3>
          <p class="text-sm text-gray-400 mt-0.5">{{ __('AI-detected damage from saved inspections') }}</p>
        </div>
        <div class="px-4 pb-5 overflow-y-auto max-h-[320px] space-y-2">
          @forelse ($recentFindings as $finding)
            <div class="rounded-xl border border-gray-100 p-3">
              <div class="flex items-start justify-between gap-3">
                <div>
                  <p class="text-sm font-medium">{{ $finding->category }}</p>
                  <p class="mt-0.5 text-xs text-gray-400">{{ $finding->inspection->property_name }}</p>
                </div>
                <span class="rounded-lg px-2 py-1 text-[10px] font-medium {{ $severityClasses[$finding->severity] ?? 'bg-gray-100 text-gray-600' }}">
                  {{ Str::headline($finding->severity) }}
                </span>
              </div>
              <div class="mt-3 flex items-center justify-between text-xs text-gray-500">
                <span>{{ number_format($finding->confidence, 1) }}% confidence</span>
                <span>Rp {{ number_format($finding->estimated_repair_cost, 0, ',', '.') }}</span>
              </div>
            </div>
          @empty
            <p class="px-3 py-8 text-center text-sm text-gray-400">{{ __('No findings available.') }}</p>
          @endforelse
        </div>
      </div>
    </div>
  </div>

  <div id="scanOverlay" class="hidden fixed inset-0 z-50 items-center justify-center bg-white/80 backdrop-blur-md p-4">
    <div class="w-full max-w-md rounded-2xl border border-gray-100 bg-white p-6 shadow-xl">
      <div class="mb-5 text-center">
        <div class="mx-auto mb-4 h-14 w-14 spin-anim rounded-full border-4 border-[#4f6ef7]/20 border-t-[#4f6ef7]"></div>
        <h3 class="text-lg font-semibold">{{ __('Analyzing Images') }}</h3>
        <p class="mt-1 text-sm text-gray-500">{{ __('AI is scanning uploaded property photos.') }}</p>
      </div>
      <div class="mb-4 h-2 overflow-hidden rounded-full bg-gray-100">
        <div id="scanProgressBar" class="h-full rounded-full bg-[#4f6ef7]" style="width: 0%"></div>
      </div>
      <div class="flex justify-between text-xs text-gray-400">
        <span>InspectAI v2.4</span>
        <span id="scanProgressText">0%</span>
      </div>
      <div id="scanSteps" class="mt-5 space-y-2"></div>
    </div>
  </div>

  <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
    <div class="mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
      <h3 class="text-base font-semibold tracking-tight">{{ __('Inspection list') }}</h3>
      <p class="text-sm text-gray-400">{{ __(':count matched', ['count' => $inspections->total()]) }}</p>
    </div>
    <form id="inspectionFilterForm" method="GET" action="{{ route('inspections.index') }}" class="mb-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-[1fr_180px_180px_180px_auto]">
      <input name="search" value="{{ $filters['search'] }}" class="h-10 rounded-xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none focus:border-[#4f6ef7] focus:bg-white" placeholder="{{ __('Search inspections by property or room...') }}">
      <select id="inspectionListWorkspaceSelect" name="workspace_id" class="h-10 rounded-xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none focus:border-[#4f6ef7] focus:bg-white">
        @foreach ($workspaces as $workspace)
          <option value="{{ $workspace->id }}" @selected((int) $filters['workspace_id'] === $workspace->id)>{{ $workspace->name }}</option>
        @endforeach
      </select>
      <select id="inspectionListCollectionSelect" name="collection_id" class="h-10 rounded-xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none focus:border-[#4f6ef7] focus:bg-white">
        <option value="">{{ __('All collections') }}</option>
        @foreach ($collections as $collection)
          <option value="{{ $collection->id }}" @selected((int) $filters['collection_id'] === $collection->id)>{{ $collection->displayName() }}</option>
        @endforeach
      </select>
      <select name="status" class="h-10 rounded-xl border border-gray-200 bg-gray-50 px-4 text-sm outline-none focus:border-[#4f6ef7] focus:bg-white">
        <option value="">{{ __('All status') }}</option>
        @foreach (['completed', 'review', 'scanning', 'scheduled'] as $status)
          <option value="{{ $status }}" @selected($filters['status'] === $status)>{{ Str::headline($status) }}</option>
        @endforeach
      </select>
      <button class="h-10 rounded-xl bg-[#4f6ef7] px-4 text-sm font-medium text-white">{{ __('Apply') }}</button>
    </form>
    <div class="overflow-x-auto">
      <table class="w-full text-left text-sm">
        <thead class="text-xs uppercase text-gray-400">
          <tr>
            <th class="px-3 py-3">{{ __('Property') }}</th>
            <th class="px-3 py-3">{{ __('Collection') }}</th>
            <th class="px-3 py-3">{{ __('Status') }}</th>
            <th class="px-3 py-3">{{ __('Confidence') }}</th>
            <th class="px-3 py-3">{{ __('Findings') }}</th>
            <th class="px-3 py-3">{{ __('Schedule') }}</th>
            <th class="px-3 py-3">{{ __('Report') }}</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-100">
          @forelse ($inspections as $inspection)
            <tr>
              <td class="px-3 py-3"><p class="font-medium">{{ $inspection->property_name }}</p><p class="mt-0.5 text-xs text-gray-400">{{ $inspection->property_address }}</p></td>
              <td class="px-3 py-3">
                <p class="text-sm font-medium">{{ $inspection->collection?->displayName() ?? __('Unbatched') }}</p>
                <p class="mt-0.5 text-xs text-gray-400">{{ Str::headline($inspection->collection?->collection_type ?? 'single') }}</p>
              </td>
              <td class="px-3 py-3"><span class="rounded-lg px-2 py-1 text-xs font-medium {{ $statusClasses[$inspection->status] ?? 'bg-gray-100 text-gray-600' }}">{{ Str::headline($inspection->status) }}</span></td>
              <td class="px-3 py-3">{{ number_format($inspection->ai_confidence, 1) }}%</td>
              <td class="px-3 py-3">{{ $inspection->damage_findings_count }}</td>
              <td class="px-3 py-3">{{ $inspection->scheduled_at?->format('M d, Y') ?? '-' }}</td>
              <td class="px-3 py-3 text-[#4f6ef7]">{{ Str::headline($inspection->report?->status ?? 'No report') }}</td>
            </tr>
          @empty
            <tr><td colspan="7" class="px-3 py-10 text-center text-sm text-gray-400">{{ __('No inspections match the current filters.') }}</td></tr>
          @endforelse
        </tbody>
      </table>
    </div>
    <div class="mt-5">{{ $inspections->links() }}</div>
  </div>

  <div id="scanImageModal" class="fixed inset-0 z-[70] hidden items-center justify-center bg-black/80 p-4">
    <div class="relative w-full max-w-6xl">
      <button type="button" onclick="closeScanImageModal()" class="absolute right-0 top-0 z-10 rounded-lg bg-white/90 px-3 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-white">Close</button>
      <div class="overflow-hidden rounded-2xl bg-white shadow-2xl">
        <img id="scanImageModalImg" src="" alt="Roboflow result detail" class="max-h-[82vh] w-full object-contain bg-gray-950">
        <div class="border-t border-gray-100 px-4 py-3">
          <p id="scanImageModalTitle" class="truncate text-sm font-medium text-gray-700"></p>
        </div>
      </div>
    </div>
  </div>
@endsection

@push('scripts')
<script data-page-script>
  var uploadedFiles = [];
  var analysisPhase = 'idle';
  var scanRequestUrl = @json(route('inspections.scan'));
  var csrfToken = @json(csrf_token());
  var inspectionUiText = {
    oneReport: @json(__('1 report')),
    reports: @json(__('reports')),
    chooseUpToReports: @json(__('Choose up to 3 extra report styles.')),
    scanningUploadedPhotos: @json(__('Scanning uploaded photos')),
    savingReport: @json(__('Saving report')),
  };

  function workspacePayload() {
    const workspaceSelect = document.getElementById('workspaceSelect');
    const workspaceName = document.getElementById('workspaceNameInput')?.value.trim() || '';
    const workspaceId = workspaceSelect?.value || '';

    return { workspaceId, workspaceName };
  }

  function updateWorkspaceInputs() {
    const { workspaceId } = workspacePayload();
    const collectionSelect = document.getElementById('collectionSelect');
    document.getElementById('workspaceNameWrap')?.classList.toggle('hidden', workspaceId !== '__new');
    if (workspaceId === '__new') {
      if (collectionSelect) collectionSelect.value = '';
    }

    if (collectionSelect) {
      Array.from(collectionSelect.options).forEach((option) => {
        const optionWorkspace = option.dataset.workspaceId;
        option.hidden = Boolean(option.value) && workspaceId !== '__new' && optionWorkspace !== workspaceId;
      });

      const selected = collectionSelect.selectedOptions[0];
      if (selected?.hidden) {
        collectionSelect.value = '';
      }
    }
  }

  function selectedGroqModels() {
    const mode = selectedScanMode();
    const models = {
      quick: ['meta-llama/llama-4-scout-17b-16e-instruct'],
      detail: ['meta-llama/llama-4-scout-17b-16e-instruct', 'openai/gpt-oss-120b'],
      deep: ['meta-llama/llama-4-scout-17b-16e-instruct', 'openai/gpt-oss-120b', 'groq/compound'],
    };

    return models[mode] || models.quick;
  }

  function selectedScanMode() {
    return document.querySelector('.scan-mode:checked')?.value || 'quick';
  }

  function selectedRoboflowModel() {
    return document.querySelector('.roboflow-model:checked')?.value || 'modelv1-low';
  }

  function effectiveGroqModels() {
    const models = selectedGroqModels();
    const researchEnabled = document.getElementById('priceResearchToggle')?.checked;
    const hasResearchModel = models.includes('groq/compound') || models.includes('groq/compound-mini');

    if (researchEnabled && !hasResearchModel) {
      return [...models.slice(0, 2), 'groq/compound'].slice(0, 3);
    }

    return models.slice(0, 3);
  }

  function selectedReportPoints() {
    const preset = document.getElementById('reportFocusPreset')?.value || 'complete';
    const presets = {
      complete: ['materials', 'labor', 'urgency', 'safety'],
      cost: ['materials', 'labor'],
      safety: ['urgency', 'safety'],
      maintenance: ['materials', 'preventive_maintenance'],
    };

    if (preset !== 'custom') {
      return presets[preset] || presets.complete;
    }

    return Array.from(document.querySelectorAll('.report-point:checked')).map(input => input.value);
  }

  function enforceModelLimit(changedInput = null) {
    const reportCount = Math.max(1, effectiveGroqModels().length);
    document.getElementById('modelCountLabel')?.replaceChildren(document.createTextNode(reportCount === 1 ? inspectionUiText.oneReport : `${reportCount} ${inspectionUiText.reports}`));
  }

  function updateOptionalPanels() {
    const sourcesEnabled = document.getElementById('customSourcesToggle')?.checked;
    document.getElementById('customSourcesPanel')?.classList.toggle('hidden', !sourcesEnabled);

    const expertEnabled = document.getElementById('expertSettingsToggle')?.checked;
    document.getElementById('expertSettingsPanel')?.classList.toggle('hidden', !expertEnabled);

    const reportFocusPreset = document.getElementById('reportFocusPreset')?.value || 'complete';
    document.getElementById('reportFocusCustomPanel')?.classList.toggle('hidden', reportFocusPreset !== 'custom');
    const help = {
      complete: {!! json_encode(__('Covers damage, cost, labor, urgency, and safety.'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) !!},
      cost: {!! json_encode(__('Focuses on materials, worker cost, and total repair estimate.'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) !!},
      safety: {!! json_encode(__('Focuses on risk level, urgency, and what needs attention first.'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) !!},
      maintenance: {!! json_encode(__('Focuses on prevention and maintenance steps after repair.'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) !!},
      custom: {!! json_encode(__('Choose the exact points you want in the report.'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) !!},
    };
    document.getElementById('reportFocusHelp')?.replaceChildren(document.createTextNode(help[reportFocusPreset] || help.complete));
    updateScanModeCards();
    updateRoboflowModelCards();
  }

  function updateScanModeCards() {
    const mode = selectedScanMode();
    const help = {
      quick: {!! json_encode(__('Good for quick checks and small repairs.'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) !!},
      detail: {!! json_encode(__('Adds a stronger second review for cost and repair notes.'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) !!},
      deep: {!! json_encode(__('Best for important reports with price research and extra review.'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) !!},
    };
    document.getElementById('scanModeHelp')?.replaceChildren(document.createTextNode(help[mode] || help.quick));
    document.querySelectorAll('.scan-mode-card').forEach((card) => {
      const active = card.querySelector('.scan-mode')?.value === mode;
      card.classList.toggle('border-[#c7d3fc]', active);
      card.classList.toggle('bg-[#eff3fe]', active);
      card.classList.toggle('text-[#4f6ef7]', active);
      card.classList.toggle('border-transparent', !active);
      card.classList.toggle('bg-transparent', !active);
      card.classList.toggle('text-gray-500', !active);
    });
  }

  function updateRoboflowModelCards() {
    const model = selectedRoboflowModel();
    document.querySelectorAll('.roboflow-model-card').forEach((card) => {
      const active = card.querySelector('.roboflow-model')?.value === model;
      card.classList.toggle('border-[#4f6ef7]', active);
      card.classList.toggle('bg-[#eff3fe]', active);
      card.classList.toggle('border-gray-100', !active);
      card.classList.toggle('bg-gray-50', !active);
    });
  }

  function setScanOverlayVisible(visible) {
    const overlay = document.getElementById('scanOverlay');
    if (!overlay) return;
    overlay.classList.toggle('hidden', !visible);
    overlay.classList.toggle('flex', visible);
    overlay.classList.toggle('active', visible);
  }

  function setSuccessPanelVisible(visible) {
    const panel = document.getElementById('successPanel');
    if (!panel) return;
    panel.classList.toggle('hidden', !visible);
    panel.classList.toggle('block', visible);
    panel.classList.toggle('active', visible);
  }

  function onDragOver(e) { e.preventDefault(); e.stopPropagation(); document.getElementById('dropZone').classList.add('dragging'); }
  function onDragLeave(e) { e.preventDefault(); e.stopPropagation(); document.getElementById('dropZone').classList.remove('dragging'); }
  function onDrop(e) {
    e.preventDefault(); e.stopPropagation();
    document.getElementById('dropZone').classList.remove('dragging');
    const files = Array.from(e.dataTransfer.files).filter(f => f.type.startsWith('image/'));
    if (files.length) addFiles(files);
  }
  function onFileInput(e) {
    const files = Array.from(e.target.files).filter(f => f.type.startsWith('image/'));
    if (files.length) addFiles(files);
    e.target.value = '';
  }

  function addFiles(files) {
    const entries = files.slice(0, 20 - uploadedFiles.length).map(f => ({
      id: Date.now() + '-' + Math.random().toString(36).slice(2, 8),
      file: f,
      preview: URL.createObjectURL(f),
      progress: 0,
      status: 'uploading'
    }));
    uploadedFiles = [...uploadedFiles, ...entries];
    analysisPhase = 'idle';
    renderUI();

    entries.forEach(entry => {
      let prog = 0;
      const iv = setInterval(() => {
        prog += Math.random() * 25 + 12;
        if (prog >= 100) {
          prog = 100;
          clearInterval(iv);
          uploadedFiles = uploadedFiles.map(f => f.id === entry.id ? { ...f, progress: 100, status: 'uploaded' } : f);
        } else {
          uploadedFiles = uploadedFiles.map(f => f.id === entry.id ? { ...f, progress: Math.round(prog) } : f);
        }
        renderUI();
      }, 350 + Math.random() * 250);
    });

    showToast(`${entries.length} image${entries.length > 1 ? 's' : ''} added to inspection queue`);
  }

  function removeFile(id) {
    const file = uploadedFiles.find(f => f.id === id);
    if (file) URL.revokeObjectURL(file.preview);
    uploadedFiles = uploadedFiles.filter(f => f.id !== id);
    analysisPhase = 'idle';
    renderUI();
  }

  function renderUI() {
    const hasFiles = uploadedFiles.length > 0;
    const allUploaded = uploadedFiles.length > 0 && uploadedFiles.every(f => f.status === 'uploaded');
    document.getElementById('dropTextEmpty').classList.toggle('hidden', hasFiles);
    document.getElementById('dropTextHasFiles').classList.toggle('hidden', !hasFiles);
    document.getElementById('previewSection').classList.toggle('hidden', !hasFiles);
    document.getElementById('headerBadges').classList.toggle('hidden', !hasFiles);
    document.getElementById('headerBadges').classList.toggle('flex', hasFiles);
    document.getElementById('analysisReadyBadge').classList.toggle('hidden', analysisPhase !== 'complete');
    document.getElementById('analysisReadyBadge').classList.toggle('flex', analysisPhase === 'complete');
    document.getElementById('analyzeWrap').classList.toggle('hidden', !allUploaded || analysisPhase === 'scanning');

    if (hasFiles) {
      const countText = `${uploadedFiles.length} image${uploadedFiles.length > 1 ? 's' : ''}`;
      document.getElementById('dropTextTitle').textContent = `${countText} selected`;
      document.getElementById('imgCountBadge').textContent = countText;
      document.getElementById('dropZone').classList.remove('py-16');
      document.getElementById('dropZone').classList.add('py-8');
    } else {
      document.getElementById('dropZone').classList.add('py-16');
      document.getElementById('dropZone').classList.remove('py-8');
    }

    const uploaded = uploadedFiles.filter(f => f.status === 'uploaded').length;
    document.getElementById('imgCountLabel').textContent = uploadedFiles.length;
    document.getElementById('uploadProgress').textContent = `${uploaded} of ${uploadedFiles.length} uploaded`;
    renderGrid();
  }

  function renderGrid() {
    document.getElementById('imgGrid').innerHTML = uploadedFiles.map(f => `
      <div class="img-card group relative overflow-hidden rounded-xl border border-gray-100 bg-white shadow-sm">
        <div class="relative aspect-[4/3] overflow-hidden bg-gray-100">
          <img src="${f.preview}" alt="${f.file.name}" class="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105">
          ${f.status === 'uploading' ? `<div class="absolute inset-0 flex flex-col items-center justify-center bg-black/40 backdrop-blur-[2px]"><div class="mb-2 h-8 w-8 spin-anim rounded-full border-2 border-white/30 border-t-white"></div><span class="text-xs font-medium text-white">${f.progress}%</span></div>` : ''}
          ${f.status === 'uploaded' ? `<div class="absolute right-2 top-2 flex h-6 w-6 items-center justify-center rounded-full bg-emerald-500 shadow-sm"><svg class="h-3.5 w-3.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg></div>` : ''}
          ${analysisPhase !== 'scanning' ? `<button onclick="event.stopPropagation(); removeFile('${f.id}')" class="remove-btn absolute left-2 top-2 flex h-6 w-6 items-center justify-center rounded-full bg-black/50 text-white backdrop-blur-sm hover:bg-rose-500 transition-colors"><svg class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg></button>` : ''}
        </div>
        <div class="p-2">
          <p class="truncate text-xs font-medium">${f.file.name}</p>
          <p class="text-[10px] text-gray-400">${(f.file.size/1024/1024).toFixed(1)} MB</p>
          ${f.status === 'uploading' ? `<div class="mt-1.5 h-1 w-full overflow-hidden rounded-full bg-gray-100"><div class="h-full rounded-full bg-[#4f6ef7] transition-all duration-300" style="width:${f.progress}%"></div></div>` : ''}
        </div>
      </div>
    `).join('');
  }

  const scanSteps = ['Scanning images', 'Detecting anomalies', 'AI classification', 'Generating report', 'Analysis complete'];

  function renderScanSteps(currentStep) {
    document.getElementById('scanSteps').innerHTML = scanSteps.map((label, i) => {
      const done = i < currentStep;
      const active = i === currentStep;
      return `<div class="flex items-center gap-3 rounded-xl px-4 py-2.5 transition-all duration-300 ${done ? 'bg-emerald-50' : active ? 'bg-[#eff3fe] border border-[#c7d3fc]' : 'opacity-40'}">
        <div class="flex h-7 w-7 shrink-0 items-center justify-center rounded-full ${done ? 'bg-emerald-500 text-white' : active ? 'bg-[#4f6ef7] text-white' : 'bg-gray-100 text-gray-400'}">${done ? '✓' : i + 1}</div>
        <span class="text-sm font-medium ${done ? 'text-emerald-600' : active ? 'text-[#4f6ef7]' : 'text-gray-400'}">${label}</span>
        ${active ? `<div class="ml-auto h-4 w-4 spin-anim rounded-full border-2 border-[#4f6ef7]/30 border-t-[#4f6ef7]"></div>` : ''}
      </div>`;
    }).join('');
  }

  function selectedMarketplaces() {
    if (!document.getElementById('customSourcesToggle')?.checked) {
      return [];
    }

    return Array.from(document.querySelectorAll('.marketplace:checked')).map(input => input.value);
  }

  function selectedOutputLabels() {
    const modeLabel = document.querySelector('.scan-mode:checked')?.closest('label')?.querySelector('.block')?.textContent?.trim() || inspectionUiText.oneReport;

    return [inspectionUiText.scanningUploadedPhotos, modeLabel, inspectionUiText.savingReport];
  }

  renderScanSteps = function(currentStep, labels = selectedOutputLabels()) {
    document.getElementById('scanSteps').innerHTML = labels.map((label, i) => {
      const done = i < currentStep;
      const active = i === currentStep;
      return `<div class="flex items-center gap-3 rounded-xl px-4 py-2.5 transition-all duration-300 ${done ? 'bg-emerald-50' : active ? 'bg-[#eff3fe] border border-[#c7d3fc]' : 'opacity-40'}">
        <div class="flex h-7 w-7 shrink-0 items-center justify-center rounded-full ${done ? 'bg-emerald-500 text-white' : active ? 'bg-[#4f6ef7] text-white' : 'bg-gray-100 text-gray-400'}">${done ? '✓' : i + 1}</div>
        <span class="text-sm font-medium ${done ? 'text-emerald-600' : active ? 'text-[#4f6ef7]' : 'text-gray-400'}">${label}</span>
        ${active ? `<div class="ml-auto h-4 w-4 spin-anim rounded-full border-2 border-[#4f6ef7]/30 border-t-[#4f6ef7]"></div>` : ''}
      </div>`;
    }).join('');
  }

  async function startAnalysis() {
    if (!uploadedFiles.length || !uploadedFiles.every(f => f.status === 'uploaded')) {
      showToast('Please wait until all images finish uploading.');
      return;
    }

    const { workspaceId, workspaceName } = workspacePayload();
    const selectedCollection = document.getElementById('collectionSelect').value;
    const propertyName = document.getElementById('propertyNameInput').value.trim();
    if (workspaceId === '__new' && workspaceName.length < 2) {
      showToast('Please enter a workspace name first.');
      return;
    }
    if (!selectedCollection && propertyName.length < 2) {
      showToast('Please choose an existing collection or enter a house/property name.');
      return;
    }

    analysisPhase = 'scanning';
    setScanOverlayVisible(true);
    setSuccessPanelVisible(false);
    renderUI();

    let elapsed = 0;
    let progress = 0;
    const outputLabels = selectedOutputLabels();
    renderScanSteps(0, outputLabels);

    const iv = setInterval(() => {
      elapsed += 250;
      progress = Math.min(progress + Math.max(2, 12 - Math.floor(elapsed / 1000)), 92);
      const pct = progress;
      document.getElementById('scanProgressBar').style.width = pct + '%';
      document.getElementById('scanProgressText').textContent = Math.round(pct) + '%';
      renderScanSteps(Math.min(Math.floor((pct / 100) * outputLabels.length), outputLabels.length - 1), outputLabels);
    }, 250);

    try {
      const formData = new FormData();
      uploadedFiles.forEach((entry) => formData.append('images[]', entry.file));
      if (workspaceId === '__new') {
        formData.append('workspace_name', workspaceName);
      } else if (workspaceId) {
        formData.append('workspace_id', workspaceId);
      }
      if (selectedCollection) {
        formData.append('collection_id', selectedCollection);
      }
      formData.append('collection_type', document.getElementById('roomNameInput').value.trim() ? 'room' : 'house');
      formData.append('property_name', propertyName);
      formData.append('property_address', document.getElementById('propertyAddressInput').value.trim());
      formData.append('room_name', document.getElementById('roomNameInput').value.trim());
      formData.append('roboflow_model', selectedRoboflowModel());
      formData.append('currency', document.getElementById('currencySelect').value);
      formData.append('output_language', document.getElementById('outputLanguageSelect').value);
      const scanMode = selectedScanMode();
      const detailByMode = { quick: 'quick', detail: 'breakdown', deep: 'scope' };
      const researchByMode = { quick: 'basic', detail: 'standard', deep: 'deep' };
      formData.append('detail_level', detailByMode[scanMode] || 'quick');
      formData.append('price_research', (scanMode === 'deep' || document.getElementById('priceResearchToggle').checked) ? '1' : '0');
      formData.append('research_depth', researchByMode[scanMode] || 'standard');
      formData.append('source_link_mode', document.getElementById('sourceLinkModeSelect').value);
      formData.append('labor_pricing_mode', document.getElementById('laborPricingModeSelect').value);
      formData.append('labor_detail_level', document.getElementById('laborDetailLevelSelect').value);
      formData.append('include_service_recommendations', document.getElementById('includeServicesToggle').checked ? '1' : '0');
      selectedMarketplaces().forEach((marketplace) => formData.append('marketplaces[]', marketplace));
      formData.append('temperature', document.getElementById('temperatureInput').value);
      formData.append('max_tokens', document.getElementById('maxTokensInput').value);
      selectedGroqModels().forEach((model) => formData.append('models[]', model));
      selectedReportPoints().forEach((point) => formData.append('report_points[]', point));

      const response = await fetch(scanRequestUrl, {
        method: 'POST',
        headers: {
          'X-CSRF-TOKEN': csrfToken,
          'X-Requested-With': 'XMLHttpRequest',
          'Accept': 'application/json'
        },
        body: formData
      });

      const payload = await response.json().catch(() => ({}));

      if (!response.ok) {
        throw new Error(payload.message || 'Roboflow scan failed.');
      }

      clearInterval(iv);
      document.getElementById('scanProgressBar').style.width = '100%';
      document.getElementById('scanProgressText').textContent = '100%';
      renderScanSteps(outputLabels.length, outputLabels);

      setTimeout(() => {
        setScanOverlayVisible(false);
        analysisPhase = 'complete';
        const summary = payload.scan_summary || {};
        const detected = Number(summary.detected ?? uploadedFiles.length);
        const failed = Number(summary.failed ?? 0);
        document.getElementById('successSubtitle').textContent = failed > 0
          ? `${detected} image${detected > 1 ? 's' : ''} analyzed, ${failed} failed Roboflow detection`
          : `${detected} image${detected > 1 ? 's' : ''} processed and saved`;
        renderRoboflowResults(payload);
        if (payload.inspection?.report_url) {
          document.getElementById('fullReportLink').href = payload.inspection.report_url;
        }
        setSuccessPanelVisible(true);
        renderUI();
        document.getElementById('successPanel')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
        showToast(failed > 0 ? 'Analysis complete with failed images skipped.' : 'Roboflow analysis complete.');
      }, 350);
    } catch (error) {
      clearInterval(iv);
      setScanOverlayVisible(false);
      analysisPhase = 'idle';
      renderUI();
      showToast(error.message || 'Roboflow scan failed.');
    }
  }

  function renderRoboflowResults(payload) {
    const wrap = document.getElementById('roboflowResults');
    const results = Array.isArray(payload.results) ? payload.results : [];
    const failedResults = Array.isArray(payload.failed_results) ? payload.failed_results : [];
    const analyses = Array.isArray(payload.groq_analyses) ? payload.groq_analyses : [];

    if (!results.length && !failedResults.length && !analyses.length) {
      wrap.classList.add('hidden');
      wrap.innerHTML = '';
      return;
    }

    wrap.classList.remove('hidden');
    const inspection = payload.inspection || {};
    const findingCount = Number(inspection.findings_count ?? 0);
    const detectionCount = Number(inspection.detection_count ?? payload.scan_summary?.detections ?? 0);
    const findingSummary = detectionCount > 0
      ? `${findingCount} findings from ${detectionCount} Roboflow detection${detectionCount > 1 ? 's' : ''}.`
      : `${findingCount} findings stored in history and report.`;

    wrap.innerHTML = `
      ${inspection.report_number ? `
        <div class="rounded-xl border border-emerald-100 bg-emerald-50 p-3">
          <p class="text-sm font-semibold text-emerald-700">${escapeHtml(inspection.report_number)} saved</p>
          <p class="mt-1 text-xs text-emerald-600">${escapeHtml(findingSummary)} Findings are grouped report issues, not raw boxes.</p>
        </div>
      ` : ''}
      ${failedResults.length ? `
        <div class="rounded-xl border border-amber-100 bg-amber-50 p-3">
          <p class="text-sm font-semibold text-amber-700">${failedResults.length} image${failedResults.length > 1 ? 's' : ''} skipped</p>
          <p class="mt-1 text-xs text-amber-600">Roboflow did not detect a home inspection issue in these images.</p>
          <div class="mt-2 flex flex-wrap gap-2">
            ${failedResults.map(result => `<span class="rounded-full bg-white/70 px-2.5 py-1 text-[11px] font-medium text-amber-700">${escapeHtml(result.file || 'image')}</span>`).join('')}
          </div>
        </div>
      ` : ''}
      <div class="space-y-3">
        ${results.map(renderRoboflowResultCard).join('')}
      </div>
      ${analyses.length ? `
        <div class="space-y-3">
          <p class="text-sm font-medium">Advanced Report Outputs</p>
          ${analyses.map(renderGroqAnalysisCard).join('')}
        </div>
      ` : ''}
    `;
  }

  function renderRoboflowResultCard(result, index) {
    const images = Array.isArray(result.output_images) ? result.output_images : [];

    return `
      <div class="rounded-xl border border-gray-100 bg-gray-50 p-3">
        <div class="mb-3 flex items-center justify-between gap-3">
          <p class="truncate text-sm font-medium">Roboflow Output ${index + 1}: ${escapeHtml(result.file || `Image ${index + 1}`)}</p>
          <span class="text-xs text-gray-400">${escapeHtml(result.detection_count ?? 0)} detections</span>
        </div>
        ${images.length ? `
          <div class="mb-3 grid grid-cols-1 gap-3">
            ${images.map(image => `
              <figure class="overflow-hidden rounded-xl border border-gray-100 bg-white">
                <button type="button" onclick="openScanImageModal('${escapeJs(image.url)}', '${escapeJs(image.key)}')" class="block w-full bg-gray-950">
                  <img src="${escapeHtml(image.url)}" alt="${escapeHtml(image.key)}" class="h-[420px] w-full object-contain">
                </button>
                <figcaption class="flex items-center justify-between gap-3 px-3 py-2 text-xs text-gray-500">
                  <span class="truncate">${escapeHtml(image.key)}</span>
                  <button type="button" onclick="openScanImageModal('${escapeJs(image.url)}', '${escapeJs(image.key)}')" class="shrink-0 rounded-lg border border-gray-200 px-2 py-1 text-[11px] font-medium hover:bg-gray-50">Detail</button>
                </figcaption>
              </figure>
            `).join('')}
          </div>
        ` : ''}
      </div>
    `;
  }

  function renderGroqAnalysisCard(analysis) {
    const content = analysis.content || {};
    const findings = Array.isArray(content.findings) ? content.findings.slice(0, 4) : [];

    return `
      <div class="rounded-xl border border-gray-100 bg-white p-4 shadow-sm">
        <div class="mb-3 flex items-center justify-between gap-3">
          <p class="text-sm font-semibold">${escapeHtml(analysis.label || analysis.model)}</p>
          <span class="rounded-full bg-[#eff3fe] px-2.5 py-1 text-xs font-medium text-[#4f6ef7]">${escapeHtml(analysis.kind || 'model')}</span>
        </div>
        ${analysis.fallback_from ? `<p class="mb-2 rounded-lg bg-amber-50 px-3 py-2 text-xs text-amber-700">Fallback used because ${escapeHtml(analysis.fallback_from)} was rate limited.</p>` : ''}
        <p class="text-sm leading-6 text-gray-600">${escapeHtml(content.summary || analysis.raw_text || 'Analysis saved to report.')}</p>
        ${findings.length ? `
          <div class="mt-3 grid gap-2">
            ${findings.map(finding => `
              <div class="rounded-lg bg-gray-50 p-3">
                <div class="flex items-center justify-between gap-3">
                  <p class="text-xs font-semibold text-gray-700">${escapeHtml(finding.category || 'Home inspection finding')}</p>
                  <span class="text-[11px] text-gray-400">${escapeHtml(finding.severity || 'medium')}</span>
                </div>
                <p class="mt-1 text-xs leading-5 text-gray-500">${escapeHtml(finding.suggested_fix || finding.evidence || '')}</p>
              </div>
            `).join('')}
          </div>
        ` : ''}
      </div>
    `;
  }

  function escapeHtml(value) {
    return String(value ?? '').replace(/[&<>"']/g, (char) => ({
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#039;'
    }[char]));
  }

  function escapeJs(value) {
    return String(value ?? '').replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n').replace(/\r/g, '');
  }

  function openScanImageModal(url, title) {
    document.getElementById('scanImageModalImg').src = url;
    document.getElementById('scanImageModalTitle').textContent = title;
    document.getElementById('scanImageModal').classList.remove('hidden');
    document.getElementById('scanImageModal').classList.add('flex');
  }

  function closeScanImageModal() {
    document.getElementById('scanImageModal').classList.add('hidden');
    document.getElementById('scanImageModal').classList.remove('flex');
    document.getElementById('scanImageModalImg').src = '';
  }

  function dismissResult() {
    analysisPhase = 'idle';
    setSuccessPanelVisible(false);
    renderUI();
  }

  function showToast(message) {
    const toast = document.createElement('div');
    toast.className = 'fixed bottom-6 right-6 z-[60] flex items-center gap-3 rounded-xl bg-gray-900 px-4 py-3 text-sm text-white shadow-xl';
    toast.innerHTML = `<span class="text-emerald-400">✓</span><span>${message}</span>`;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 3500);
  }

  document.querySelectorAll('.groq-model').forEach((input) => {
    input.addEventListener('change', () => enforceModelLimit(input));
  });
  document.querySelectorAll('.scan-mode').forEach((input) => {
    input.addEventListener('change', () => {
      updateOptionalPanels();
      enforceModelLimit();
    });
  });
  document.querySelectorAll('.roboflow-model').forEach((input) => {
    input.addEventListener('change', updateRoboflowModelCards);
  });
  document.getElementById('priceResearchToggle')?.addEventListener('change', () => enforceModelLimit());
  document.getElementById('customSourcesToggle')?.addEventListener('change', updateOptionalPanels);
  document.getElementById('expertSettingsToggle')?.addEventListener('change', updateOptionalPanels);
  document.getElementById('reportFocusPreset')?.addEventListener('change', updateOptionalPanels);
  document.getElementById('workspaceSelect')?.addEventListener('change', updateWorkspaceInputs);
  document.getElementById('inspectionListWorkspaceSelect')?.addEventListener('change', () => {
    const collection = document.getElementById('inspectionListCollectionSelect');
    if (collection) collection.value = '';
    document.getElementById('inspectionFilterForm')?.submit();
  });
  updateWorkspaceInputs();
  updateOptionalPanels();
  if (window.location.pathname.includes('/inspections')) {
    setTimeout(() => window.scrollTo({ top: 0, behavior: 'auto' }), 0);
  }
  enforceModelLimit();
</script>
@endpush
