@extends('layouts.app')

@section('title', $report->report_number)
@section('active', 'reports')

@section('content')
  @php
    $sourceImages = $inspection->source_image_paths ?? [];
    $visualizationImages = $inspection->visualization_image_paths ?? [];
    $groqAnalyses = $inspection->groq_analysis_outputs ?? [];
    $settings = $inspection->analysis_settings ?? [];
    $roboflowDetectionCount = (int) ($settings['roboflow_detection_count'] ?? collect($inspection->roboflow_outputs ?? [])->sum(fn ($result) => (int) data_get($result, 'detection_count', 0)));
    $shoppingRecommendations = collect($groqAnalyses)
      ->flatMap(fn ($analysis) => data_get($analysis, 'content.shopping_recommendations', data_get($analysis, 'content.recommended_products', [])))
      ->filter(fn ($item) => is_array($item))
      ->values();
    $laborPlans = collect($groqAnalyses)
      ->map(fn ($analysis) => data_get($analysis, 'content.labor_plan'))
      ->filter(fn ($plan) => is_array($plan))
      ->values();
    $totalEstimates = collect($groqAnalyses)
      ->map(fn ($analysis) => data_get($analysis, 'content.total_estimate'))
      ->filter(fn ($estimate) => is_array($estimate))
      ->values();
    $aiFindingDetails = collect($groqAnalyses)
      ->flatMap(fn ($analysis) => data_get($analysis, 'content.findings', []))
      ->filter(fn ($finding) => is_array($finding))
      ->values();
    $pointLabels = [
      'materials' => __('Materials'),
      'labor' => __('Labor'),
      'urgency' => __('Urgency'),
      'safety' => __('Safety'),
      'preventive_maintenance' => __('Preventive Maintenance'),
    ];
    $severityClasses = [
      'high' => 'bg-red-50 text-red-600',
      'medium' => 'bg-amber-50 text-amber-600',
      'low' => 'bg-emerald-50 text-emerald-600',
    ];
    $marketplaceSearchUrl = function (array $item): string {
      $name = (string) data_get($item, 'item_name', data_get($item, 'item', data_get($item, 'material', 'home repair material')));
      $store = Str::of((string) data_get($item, 'store_name', data_get($item, 'store', 'Tokopedia')))->lower()->replace([' ', '-', '_'], '')->toString();
      $query = rawurlencode(Str::lower($name));

      return match (true) {
        str_contains($store, 'shopee') => "https://shopee.co.id/search?keyword={$query}",
        str_contains($store, 'ace') => "https://www.acehardware.co.id/search?query={$query}",
        str_contains($store, 'depo') => "https://depobangunan.co.id/search?keyword={$query}",
        str_contains($store, 'tukangcom'), str_contains($store, 'tukang') => 'https://tukang.com/',
        str_contains($store, 'kanggo') => 'https://www.kanggo.id/tukang-harian',
        str_contains($store, 'sejasa') => 'https://www.sejasa.com/',
        str_contains($store, 'hwb') => 'https://hwb.co.id/',
        str_contains($store, 'contractor'), str_contains($store, 'kontraktor'), str_contains($store, 'service') => 'https://www.sejasa.com/',
        default => "https://www.tokopedia.com/search?st=product&q={$query}",
      };
    };
    $safeStoreUrl = function (array $item) use ($marketplaceSearchUrl): string {
      $candidate = data_get($item, 'search_url', data_get($item, 'store_url', data_get($item, 'direct_product_url', data_get($item, 'url', data_get($item, 'source_url')))));

      if (is_string($candidate) && Str::contains(Str::lower($candidate), 'mitra10')) {
        return $marketplaceSearchUrl($item);
      }

      return is_string($candidate) && filter_var($candidate, FILTER_VALIDATE_URL) && Str::startsWith($candidate, ['https://'])
        ? $candidate
        : $marketplaceSearchUrl($item);
    };
    $safeProductImageUrl = function (array $item): ?string {
      $candidate = data_get($item, 'product_image_url',
        data_get($item, 'image_url',
          data_get($item, 'thumbnail_url',
            data_get($item, 'image',
              data_get($item, 'thumbnail')
            )
          )
        )
      );

      return is_string($candidate) && filter_var($candidate, FILTER_VALIDATE_URL) && Str::startsWith($candidate, ['https://'])
        ? $candidate
        : null;
    };
    $moneyLabel = function (mixed $value) use ($settings): string {
      if ($value === null || $value === '') {
        return '-';
      }

      $currency = strtoupper((string) ($settings['currency'] ?? 'IDR'));
      $format = fn (int $amount): string => $currency === 'USD'
        ? '$'.number_format($amount, 2, '.', ',')
        : 'Rp. '.number_format($amount, 0, ',', '.');
      $normalize = function (string $raw): int {
        $digits = preg_replace('/[^\d]/', '', $raw);

        return $digits === '' ? 0 : (int) $digits;
      };

      if (is_numeric($value)) {
        return $format((int) $value);
      }

      $text = trim((string) $value);
      if ($text === '' || $text === '-') {
        return '-';
      }

      return preg_replace_callback('/(?:Rp\.?|IDR|\$|USD)?\s*\d+(?:[.,]\d{3})*(?:[.,]\d+)?(?:\s*(?:IDR|USD))?/i', function (array $match) use ($format, $normalize) {
        $amount = $normalize($match[0]);

        return $amount > 0 ? $format($amount) : $match[0];
      }, $text) ?? $text;
    };
  @endphp

  <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
    <div>
      <a href="{{ route('reports.index') }}" data-spa-link class="text-sm font-medium text-[#4f6ef7] hover:text-[#3d5ce0]">Back to reports</a>
      <h1 class="mt-2 text-2xl font-bold tracking-tight">{{ $report->report_number }}</h1>
      <p class="mt-1 text-sm text-gray-500">{{ $inspection->property_name }} · {{ $inspection->completed_at?->format('M d, Y H:i') }}</p>
      @if ($inspection->collection)
        <p class="mt-1 text-sm font-medium text-[#4f6ef7]">{{ __('Collection') }}: {{ $inspection->collection->displayName() }}</p>
      @endif
    </div>
    <span class="inline-flex h-9 items-center rounded-xl bg-emerald-50 px-3 text-sm font-medium text-emerald-600">{{ Str::headline($report->status) }}</span>
  </div>

  <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-5">
    <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
      <p class="text-sm font-medium text-gray-500">Findings</p>
      <p class="mt-2 text-2xl font-bold">{{ $inspection->damageFindings->count() }}</p>
      <p class="mt-1 text-xs text-gray-400">{{ __('Grouped report issues') }}</p>
    </div>
    <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
      <p class="text-sm font-medium text-gray-500">{{ __('Roboflow Detections') }}</p>
      <p class="mt-2 text-2xl font-bold">{{ $roboflowDetectionCount }}</p>
      <p class="mt-1 text-xs text-gray-400">{{ __('Raw detection boxes') }}</p>
    </div>
    <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
      <p class="text-sm font-medium text-gray-500">Confidence</p>
      <p class="mt-2 text-2xl font-bold text-[#4f6ef7]">{{ number_format($inspection->ai_confidence, 1) }}%</p>
    </div>
    <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
      <p class="text-sm font-medium text-gray-500">Estimated Cost</p>
      <p class="mt-2 text-2xl font-bold">{{ $inspection->estimated_cost_label ?? 'Rp '.number_format($inspection->estimated_cost, 0, ',', '.') }}</p>
    </div>
    <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
      <p class="text-sm font-medium text-gray-500">Currency</p>
      <p class="mt-2 text-2xl font-bold">{{ $settings['currency'] ?? 'IDR' }}</p>
    </div>
  </div>

  @if ($inspection->collection)
    <div class="rounded-2xl border border-[#c7d3fc] bg-[#eff3fe] p-5">
      <div class="grid gap-4 md:grid-cols-3">
        <div>
          <p class="text-xs font-semibold uppercase tracking-wide text-[#4f6ef7]">{{ __('Collection') }}</p>
          <p class="mt-1 font-bold">{{ $inspection->collection->displayName() }}</p>
        </div>
        <div>
          <p class="text-xs font-semibold uppercase tracking-wide text-[#4f6ef7]">{{ __('House / Property') }}</p>
          <p class="mt-1 font-bold">{{ $inspection->collection->property_name }}</p>
        </div>
        <div>
          <p class="text-xs font-semibold uppercase tracking-wide text-[#4f6ef7]">{{ __('Room / Area') }}</p>
          <p class="mt-1 font-bold">{{ $inspection->collection->room_name ?: __('Whole property') }}</p>
        </div>
      </div>
    </div>
  @endif

  <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
    <h2 class="text-base font-semibold">Summary</h2>
    <p class="mt-2 text-sm leading-6 text-gray-500">{{ $report->summary ?? 'No summary available.' }}</p>
    @if ($groqAnalyses)
      <div class="mt-4 flex flex-wrap gap-2">
        @foreach ($groqAnalyses as $analysis)
          <span class="rounded-full border border-gray-200 bg-gray-50 px-2.5 py-1 text-xs font-medium text-gray-600">{{ $analysis['label'] ?? $analysis['model'] ?? 'AI Model' }}</span>
        @endforeach
      </div>
    @endif
    @if (! empty($settings['report_points']))
      <div class="mt-4">
        <p class="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-400">{{ __('Cost Focus') }}</p>
        <div class="flex flex-wrap gap-2">
          @foreach ($settings['report_points'] as $point)
            <span class="rounded-full border border-[#c7d3fc] bg-[#eff3fe] px-2.5 py-1 text-xs font-medium text-[#4f6ef7]">{{ $pointLabels[$point] ?? $point }}</span>
          @endforeach
        </div>
      </div>
    @endif
  </div>

  @if ($laborPlans->isNotEmpty())
    <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">
        <div>
          <h2 class="text-base font-semibold">{{ __('Labor Cost Plan') }}</h2>
          <p class="text-sm text-gray-400">{{ __('Worker roles, payment mode, duration, and labor subtotal') }}</p>
        </div>
        <span class="rounded-full bg-[#eff3fe] px-2.5 py-1 text-xs font-medium text-[#4f6ef7]">{{ Str::headline($settings['labor_pricing_mode'] ?? 'auto') }}</span>
      </div>

      @foreach ($laborPlans as $plan)
        <div class="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          <div class="rounded-xl border border-gray-100 bg-gray-50 p-3">
            <p class="text-xs font-semibold text-gray-400">{{ __('Payment Mode') }}</p>
            <p class="mt-1 text-sm font-bold">{{ data_get($plan, 'pricing_mode', $settings['labor_pricing_mode'] ?? 'auto') }}</p>
          </div>
          <div class="rounded-xl border border-gray-100 bg-gray-50 p-3">
            <p class="text-xs font-semibold text-gray-400">{{ __('Duration') }}</p>
            <p class="mt-1 text-sm font-bold">{{ data_get($plan, 'duration_estimate', '-') }}</p>
          </div>
          <div class="rounded-xl border border-gray-100 bg-gray-50 p-3">
            <p class="text-xs font-semibold text-gray-400">{{ __('Crew') }}</p>
            <p class="mt-1 text-sm font-bold">{{ data_get($plan, 'crew_summary', '-') }}</p>
          </div>
          <div class="rounded-xl border border-gray-100 bg-gray-50 p-3">
            <p class="text-xs font-semibold text-gray-400">{{ __('Labor Total') }}</p>
            <p class="mt-1 text-sm font-bold">{{ $moneyLabel(data_get($plan, 'total_labor_cost', '-')) }}</p>
          </div>
        </div>

        @php $lineItems = collect(data_get($plan, 'line_items', []))->filter(fn ($item) => is_array($item))->values(); @endphp
        @if ($lineItems->isNotEmpty())
          <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">{{ __('Role') }}</th>
                  <th class="px-3 py-3">{{ __('Task') }}</th>
                  <th class="px-3 py-3">{{ __('Workers') }}</th>
                  <th class="px-3 py-3">{{ __('Duration') }}</th>
                  <th class="px-3 py-3">{{ __('Rate') }}</th>
                  <th class="px-3 py-3">{{ __('Subtotal') }}</th>
                  <th class="px-3 py-3">{{ __('Notes') }}</th>
                </tr>
              </thead>
              <tbody class="divide-y divide-gray-100">
                @foreach ($lineItems as $item)
                  <tr>
                    <td class="px-3 py-3 font-medium">{{ data_get($item, 'role', '-') }}</td>
                    <td class="max-w-xs px-3 py-3 text-gray-500">{{ data_get($item, 'task', '-') }}</td>
                    <td class="px-3 py-3">{{ data_get($item, 'worker_count', '-') }}</td>
                    <td class="px-3 py-3">{{ data_get($item, 'duration', '-') }}</td>
                    <td class="px-3 py-3">{{ $moneyLabel(data_get($item, 'rate', '-')) }} <span class="text-xs text-gray-400">{{ data_get($item, 'rate_type', '') }}</span></td>
                    <td class="px-3 py-3 font-medium">{{ $moneyLabel(data_get($item, 'subtotal', '-')) }}</td>
                    <td class="max-w-sm px-3 py-3 text-gray-500">{{ data_get($item, 'notes', '-') }}</td>
                  </tr>
                @endforeach
              </tbody>
            </table>
          </div>
        @endif

        @if (! empty($plan['assumptions']) || ! empty($plan['exclusions']))
          <div class="mt-4 grid gap-3 md:grid-cols-2">
            <div class="rounded-xl border border-gray-100 bg-gray-50 p-3">
              <p class="text-xs font-semibold text-gray-400">{{ __('Assumptions') }}</p>
              <p class="mt-1 text-sm leading-6 text-gray-500">{{ is_array($plan['assumptions'] ?? null) ? implode('; ', $plan['assumptions']) : ($plan['assumptions'] ?? '-') }}</p>
            </div>
            <div class="rounded-xl border border-gray-100 bg-gray-50 p-3">
              <p class="text-xs font-semibold text-gray-400">{{ __('Exclusions') }}</p>
              <p class="mt-1 text-sm leading-6 text-gray-500">{{ is_array($plan['exclusions'] ?? null) ? implode('; ', $plan['exclusions']) : ($plan['exclusions'] ?? '-') }}</p>
            </div>
          </div>
        @endif
      @endforeach
    </div>
  @endif

  @if ($shoppingRecommendations->isNotEmpty() || $totalEstimates->isNotEmpty())
    <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">
        <div>
          <h2 class="text-base font-semibold">{{ __('Shopping Recommendations') }}</h2>
          <p class="text-sm text-gray-400">{{ __('AI-recommended materials, stores, and estimated totals') }}</p>
        </div>
        @if (! empty($settings['price_research']))
          <span class="rounded-full bg-[#eff3fe] px-2.5 py-1 text-xs font-medium text-[#4f6ef7]">{{ __('Price research enabled') }}</span>
        @endif
      </div>

      @if ($totalEstimates->isNotEmpty())
        <div class="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          @foreach ($totalEstimates as $estimate)
            <div class="rounded-xl border border-gray-100 bg-gray-50 p-3">
              <p class="text-xs font-semibold text-gray-400">{{ data_get($estimate, 'currency', $settings['currency'] ?? 'IDR') }}</p>
              <p class="mt-1 text-lg font-bold">{{ $moneyLabel(data_get($estimate, 'grand_total', data_get($estimate, 'total', '-'))) }}</p>
              <p class="mt-1 text-xs text-gray-500">
                {{ __('Materials') }}: {{ $moneyLabel(data_get($estimate, 'materials_total', '-')) }} · {{ __('Labor') }}: {{ $moneyLabel(data_get($estimate, 'labor_total', '-')) }}
              </p>
            </div>
          @endforeach
        </div>
      @endif

      @if ($shoppingRecommendations->isNotEmpty())
        <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">{{ __('Item') }}</th>
                <th class="px-3 py-3">{{ __('Purpose') }}</th>
                <th class="px-3 py-3">{{ __('Store') }}</th>
                <th class="px-3 py-3">{{ __('Qty') }}</th>
                <th class="px-3 py-3">{{ __('Estimated Price') }}</th>
                <th class="px-3 py-3">{{ __('Notes') }}</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">
              @foreach ($shoppingRecommendations as $item)
                @php
                  $storeUrl = $safeStoreUrl($item);
                  $storeName = data_get($item, 'store_name', data_get($item, 'store', data_get($item, 'vendor', 'Store')));
                  $price = data_get($item, 'estimated_total_price', data_get($item, 'estimated_price', data_get($item, 'price_range', data_get($item, 'estimated_unit_price', '-'))));
                @endphp
                <tr>
                  <td class="px-3 py-3 font-medium">{{ data_get($item, 'item_name', data_get($item, 'item', data_get($item, 'material', 'Repair item'))) }}</td>
                  <td class="max-w-xs px-3 py-3 text-gray-500">{{ data_get($item, 'purpose', '-') }}</td>
                  <td class="px-3 py-3">
                    @if (is_string($storeUrl) && Str::startsWith($storeUrl, ['http://', 'https://']))
                      <a href="{{ $storeUrl }}" target="_blank" rel="noopener noreferrer" class="font-medium text-[#4f6ef7] hover:text-[#3d5ce0]">{{ $storeName }}</a>
                    @else
                      <span class="text-gray-500">{{ $storeName }}</span>
                    @endif
                  </td>
                  <td class="px-3 py-3">{{ data_get($item, 'quantity', '-') }}</td>
                  <td class="px-3 py-3 font-medium">{{ $moneyLabel($price) }}</td>
                  <td class="max-w-sm px-3 py-3 text-gray-500">{{ data_get($item, 'notes', data_get($item, 'source_type', '-')) }}</td>
                </tr>
              @endforeach
            </tbody>
          </table>
        </div>
        <div class="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
          @foreach ($shoppingRecommendations as $item)
            @php
              $cardUrl = $safeStoreUrl($item);
              $productImageUrl = $safeProductImageUrl($item);
              $embedUrl = data_get($item, 'embed_url');
              $cardStore = data_get($item, 'store_name', data_get($item, 'store', 'Store'));
              $cardItemName = data_get($item, 'item_name', data_get($item, 'item', 'Repair item'));
            @endphp
            <article class="overflow-hidden rounded-xl border border-gray-100 bg-gray-50">
              @if ($productImageUrl)
                <a href="{{ $cardUrl }}" target="_blank" rel="noopener noreferrer" class="block bg-white">
                  <img src="{{ $productImageUrl }}" alt="{{ $cardItemName }}" class="h-44 w-full object-contain p-4" loading="lazy" referrerpolicy="no-referrer">
                </a>
              @elseif (is_string($embedUrl) && Str::startsWith($embedUrl, ['http://', 'https://']))
                <iframe src="{{ $embedUrl }}" title="{{ $cardItemName }}" class="h-44 w-full bg-white" loading="lazy"></iframe>
              @else
                <div class="flex h-44 flex-col items-center justify-center gap-3 bg-gradient-to-br from-slate-50 to-blue-50 px-4 text-center">
                  <div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-white text-[#4f6ef7] shadow-sm">
                    <svg viewBox="0 0 24 24" class="h-6 w-6" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                      <path d="M6 7h12l-1 13H7L6 7Z" />
                      <path d="M9 7a3 3 0 0 1 6 0" />
                    </svg>
                  </div>
                  <div>
                    <p class="text-sm font-semibold text-gray-700">{{ $cardItemName }}</p>
                    <p class="mt-1 text-xs text-gray-400">{{ __('Product image is not available yet') }}</p>
                  </div>
                </div>
              @endif
              <div class="p-3">
                <p class="text-xs font-medium text-gray-400">{{ $cardStore }}</p>
                <p class="mt-1 text-sm font-semibold">{{ $moneyLabel(data_get($item, 'estimated_total_price', data_get($item, 'estimated_unit_price', '-'))) }}</p>
                @if (is_string($cardUrl) && Str::startsWith($cardUrl, ['http://', 'https://']))
                  <a href="{{ $cardUrl }}" target="_blank" rel="noopener noreferrer" class="mt-3 inline-flex rounded-lg bg-[#4f6ef7] px-3 py-1.5 text-xs font-medium text-white hover:bg-[#3d5ce0]">{{ __('Open Store Link') }}</a>
                @endif
              </div>
            </article>
          @endforeach
        </div>
      @endif
    </div>
  @endif

  @if ($groqAnalyses)
    <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
      <div class="mb-4 flex items-center justify-between">
        <h2 class="text-base font-semibold">Advanced AI Analysis</h2>
        <p class="text-sm text-gray-400">{{ count($groqAnalyses) }} model outputs</p>
      </div>
      <div class="grid gap-4 lg:grid-cols-2">
        @foreach ($groqAnalyses as $analysis)
          @php $content = $analysis['content'] ?? []; @endphp
          <article class="rounded-xl border border-gray-100 bg-gray-50 p-4">
            <div class="mb-3 flex items-center justify-between gap-3">
              <h3 class="text-sm font-semibold">{{ $analysis['label'] ?? $analysis['model'] ?? 'AI Model' }}</h3>
              <span class="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-gray-500">{{ Str::headline($analysis['kind'] ?? 'analysis') }}</span>
            </div>
            @if (! empty($analysis['fallback_from']))
              <p class="mb-3 rounded-lg bg-amber-50 px-3 py-2 text-xs text-amber-700">
                Fallback used because {{ $analysis['fallback_from'] }} was rate limited.
              </p>
            @endif
            <p class="text-sm leading-6 text-gray-600">{{ $content['summary'] ?? $analysis['raw_text'] ?? 'Analysis saved.' }}</p>
            @if (! empty($content['recommended_next_steps']))
              <div class="mt-3">
                <p class="text-xs font-semibold text-gray-500">Recommended Next Steps</p>
                <ul class="mt-2 space-y-1 text-xs leading-5 text-gray-500">
                  @foreach ((array) $content['recommended_next_steps'] as $step)
                    <li>{{ is_array($step) ? json_encode($step) : $step }}</li>
                  @endforeach
                </ul>
              </div>
            @endif
          </article>
        @endforeach
      </div>
    </div>
  @endif

  @if ($visualizationImages)
    <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
      <div class="mb-4 flex items-center justify-between">
        <h2 class="text-base font-semibold">{{ __('Roboflow Visualizations') }}</h2>
        <p class="text-sm text-gray-400">{{ count($visualizationImages) }} image outputs</p>
      </div>
      <div class="grid gap-4 lg:grid-cols-2">
        @foreach ($visualizationImages as $image)
          <figure class="overflow-hidden rounded-xl border border-gray-100 bg-white">
            <button type="button" onclick="openReportImageModal('{{ e($image['url'] ?? '') }}', '{{ e($image['key'] ?? 'Visualization') }}')" class="block w-full bg-gray-950">
              <img src="{{ $image['url'] ?? '' }}" alt="{{ $image['key'] ?? 'Roboflow visualization' }}" class="h-[460px] 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">{{ $image['key'] ?? 'Visualization' }}</span>
              <button type="button" onclick="openReportImageModal('{{ e($image['url'] ?? '') }}', '{{ e($image['key'] ?? 'Visualization') }}')" class="rounded-lg border border-gray-200 px-2 py-1 text-[11px] font-medium hover:bg-gray-50">Detail</button>
            </figcaption>
          </figure>
        @endforeach
      </div>
    </div>
  @endif

  @if ($sourceImages)
    <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
      <h2 class="mb-4 text-base font-semibold">{{ __('Uploaded Images') }}</h2>
      <div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        @foreach ($sourceImages as $image)
          <figure class="overflow-hidden rounded-xl border border-gray-100 bg-white">
            <img src="{{ $image['url'] ?? '' }}" alt="{{ $image['name'] ?? 'Uploaded image' }}" class="h-48 w-full object-cover">
            <figcaption class="truncate px-3 py-2 text-xs text-gray-500">{{ $image['name'] ?? 'Uploaded image' }}</figcaption>
          </figure>
        @endforeach
      </div>
    </div>
  @endif

  <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
    <h2 class="mb-4 text-base font-semibold">{{ __('Findings') }}</h2>
    <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">Category</th>
            <th class="px-3 py-3">Severity</th>
            <th class="px-3 py-3">Confidence</th>
            <th class="px-3 py-3">Repair Cost</th>
            <th class="px-3 py-3">Notes</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-100">
          @forelse ($inspection->damageFindings as $finding)
            @php
              $detail = $aiFindingDetails->first(function ($item) use ($finding) {
                return Str::of((string) data_get($item, 'category'))->lower()->contains(Str::of($finding->category)->lower()->toString())
                  || Str::of($finding->category)->lower()->contains(Str::of((string) data_get($item, 'category'))->lower()->toString());
              }) ?? $aiFindingDetails->get($loop->index, []);
            @endphp
            <tr>
              <td class="px-3 py-3 font-medium">{{ $finding->category }}</td>
              <td class="px-3 py-3"><span class="rounded-lg px-2 py-1 text-xs font-medium {{ $severityClasses[$finding->severity] ?? 'bg-gray-100 text-gray-600' }}">{{ Str::headline($finding->severity) }}</span></td>
              <td class="px-3 py-3">{{ number_format($finding->confidence, 1) }}%</td>
              <td class="px-3 py-3">
                <p>{{ $moneyLabel($finding->estimated_repair_cost) }}</p>
                @if (data_get($detail, 'material_cost') || data_get($detail, 'labor_cost'))
                  <p class="mt-1 text-xs text-gray-400">{{ __('Materials') }}: {{ $moneyLabel(data_get($detail, 'material_cost', '-')) }}</p>
                  <p class="text-xs text-gray-400">{{ __('Labor') }}: {{ $moneyLabel(data_get($detail, 'labor_cost', '-')) }}</p>
                @endif
              </td>
              <td class="max-w-md px-3 py-3 text-gray-500">
                <p>{{ Str::limit($finding->notes, 120) }}</p>
                @if (data_get($detail, 'assumptions'))
                  <p class="mt-1 text-xs text-gray-400">{{ __('Assumptions') }}: {{ is_array(data_get($detail, 'assumptions')) ? implode('; ', data_get($detail, 'assumptions')) : data_get($detail, 'assumptions') }}</p>
                @endif
              </td>
            </tr>
          @empty
            <tr><td colspan="5" class="px-3 py-8 text-center text-sm text-gray-400">No prediction findings were extracted from this workflow response.</td></tr>
          @endforelse
        </tbody>
      </table>
    </div>
  </div>

  <div id="reportImageModal" 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="closeReportImageModal()" 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="reportImageModalImg" src="" alt="Report image 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="reportImageModalTitle" class="truncate text-sm font-medium text-gray-700"></p>
        </div>
      </div>
    </div>
  </div>
@endsection

@push('scripts')
<script data-page-script>
  function openReportImageModal(url, title) {
    document.getElementById('reportImageModalImg').src = url;
    document.getElementById('reportImageModalTitle').textContent = title;
    document.getElementById('reportImageModal').classList.remove('hidden');
    document.getElementById('reportImageModal').classList.add('flex');
  }

  function closeReportImageModal() {
    document.getElementById('reportImageModal').classList.add('hidden');
    document.getElementById('reportImageModal').classList.remove('flex');
    document.getElementById('reportImageModalImg').src = '';
  }
</script>
@endpush
