<?php $__env->startSection('title', $report->report_number); ?>
<?php $__env->startSection('active', 'reports'); ?>

<?php $__env->startSection('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;
    };
  ?>

  <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
    <div>
      <a href="<?php echo e(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"><?php echo e($report->report_number); ?></h1>
      <p class="mt-1 text-sm text-gray-500"><?php echo e($inspection->property_name); ?> · <?php echo e($inspection->completed_at?->format('M d, Y H:i')); ?></p>
      <?php if($inspection->collection): ?>
        <p class="mt-1 text-sm font-medium text-[#4f6ef7]"><?php echo e(__('Collection')); ?>: <?php echo e($inspection->collection->displayName()); ?></p>
      <?php endif; ?>
    </div>
    <span class="inline-flex h-9 items-center rounded-xl bg-emerald-50 px-3 text-sm font-medium text-emerald-600"><?php echo e(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"><?php echo e($inspection->damageFindings->count()); ?></p>
      <p class="mt-1 text-xs text-gray-400"><?php echo e(__('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"><?php echo e(__('Roboflow Detections')); ?></p>
      <p class="mt-2 text-2xl font-bold"><?php echo e($roboflowDetectionCount); ?></p>
      <p class="mt-1 text-xs text-gray-400"><?php echo e(__('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]"><?php echo e(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"><?php echo e($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"><?php echo e($settings['currency'] ?? 'IDR'); ?></p>
    </div>
  </div>

  <?php 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]"><?php echo e(__('Collection')); ?></p>
          <p class="mt-1 font-bold"><?php echo e($inspection->collection->displayName()); ?></p>
        </div>
        <div>
          <p class="text-xs font-semibold uppercase tracking-wide text-[#4f6ef7]"><?php echo e(__('House / Property')); ?></p>
          <p class="mt-1 font-bold"><?php echo e($inspection->collection->property_name); ?></p>
        </div>
        <div>
          <p class="text-xs font-semibold uppercase tracking-wide text-[#4f6ef7]"><?php echo e(__('Room / Area')); ?></p>
          <p class="mt-1 font-bold"><?php echo e($inspection->collection->room_name ?: __('Whole property')); ?></p>
        </div>
      </div>
    </div>
  <?php 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"><?php echo e($report->summary ?? 'No summary available.'); ?></p>
    <?php if($groqAnalyses): ?>
      <div class="mt-4 flex flex-wrap gap-2">
        <?php $__currentLoopData = $groqAnalyses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $analysis): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
          <span class="rounded-full border border-gray-200 bg-gray-50 px-2.5 py-1 text-xs font-medium text-gray-600"><?php echo e($analysis['label'] ?? $analysis['model'] ?? 'AI Model'); ?></span>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
      </div>
    <?php endif; ?>
    <?php if(! empty($settings['report_points'])): ?>
      <div class="mt-4">
        <p class="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-400"><?php echo e(__('Cost Focus')); ?></p>
        <div class="flex flex-wrap gap-2">
          <?php $__currentLoopData = $settings['report_points']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $point): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <span class="rounded-full border border-[#c7d3fc] bg-[#eff3fe] px-2.5 py-1 text-xs font-medium text-[#4f6ef7]"><?php echo e($pointLabels[$point] ?? $point); ?></span>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </div>
      </div>
    <?php endif; ?>
  </div>

  <?php 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"><?php echo e(__('Labor Cost Plan')); ?></h2>
          <p class="text-sm text-gray-400"><?php echo e(__('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]"><?php echo e(Str::headline($settings['labor_pricing_mode'] ?? 'auto')); ?></span>
      </div>

      <?php $__currentLoopData = $laborPlans; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $plan): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
        <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"><?php echo e(__('Payment Mode')); ?></p>
            <p class="mt-1 text-sm font-bold"><?php echo e(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"><?php echo e(__('Duration')); ?></p>
            <p class="mt-1 text-sm font-bold"><?php echo e(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"><?php echo e(__('Crew')); ?></p>
            <p class="mt-1 text-sm font-bold"><?php echo e(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"><?php echo e(__('Labor Total')); ?></p>
            <p class="mt-1 text-sm font-bold"><?php echo e($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(); ?>
        <?php 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"><?php echo e(__('Role')); ?></th>
                  <th class="px-3 py-3"><?php echo e(__('Task')); ?></th>
                  <th class="px-3 py-3"><?php echo e(__('Workers')); ?></th>
                  <th class="px-3 py-3"><?php echo e(__('Duration')); ?></th>
                  <th class="px-3 py-3"><?php echo e(__('Rate')); ?></th>
                  <th class="px-3 py-3"><?php echo e(__('Subtotal')); ?></th>
                  <th class="px-3 py-3"><?php echo e(__('Notes')); ?></th>
                </tr>
              </thead>
              <tbody class="divide-y divide-gray-100">
                <?php $__currentLoopData = $lineItems; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                  <tr>
                    <td class="px-3 py-3 font-medium"><?php echo e(data_get($item, 'role', '-')); ?></td>
                    <td class="max-w-xs px-3 py-3 text-gray-500"><?php echo e(data_get($item, 'task', '-')); ?></td>
                    <td class="px-3 py-3"><?php echo e(data_get($item, 'worker_count', '-')); ?></td>
                    <td class="px-3 py-3"><?php echo e(data_get($item, 'duration', '-')); ?></td>
                    <td class="px-3 py-3"><?php echo e($moneyLabel(data_get($item, 'rate', '-'))); ?> <span class="text-xs text-gray-400"><?php echo e(data_get($item, 'rate_type', '')); ?></span></td>
                    <td class="px-3 py-3 font-medium"><?php echo e($moneyLabel(data_get($item, 'subtotal', '-'))); ?></td>
                    <td class="max-w-sm px-3 py-3 text-gray-500"><?php echo e(data_get($item, 'notes', '-')); ?></td>
                  </tr>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>

        <?php 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"><?php echo e(__('Assumptions')); ?></p>
              <p class="mt-1 text-sm leading-6 text-gray-500"><?php echo e(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"><?php echo e(__('Exclusions')); ?></p>
              <p class="mt-1 text-sm leading-6 text-gray-500"><?php echo e(is_array($plan['exclusions'] ?? null) ? implode('; ', $plan['exclusions']) : ($plan['exclusions'] ?? '-')); ?></p>
            </div>
          </div>
        <?php endif; ?>
      <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
    </div>
  <?php endif; ?>

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

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

              </p>
            </div>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </div>
      <?php endif; ?>

      <?php 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"><?php echo e(__('Item')); ?></th>
                <th class="px-3 py-3"><?php echo e(__('Purpose')); ?></th>
                <th class="px-3 py-3"><?php echo e(__('Store')); ?></th>
                <th class="px-3 py-3"><?php echo e(__('Qty')); ?></th>
                <th class="px-3 py-3"><?php echo e(__('Estimated Price')); ?></th>
                <th class="px-3 py-3"><?php echo e(__('Notes')); ?></th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">
              <?php $__currentLoopData = $shoppingRecommendations; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <?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', '-'))));
                ?>
                <tr>
                  <td class="px-3 py-3 font-medium"><?php echo e(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"><?php echo e(data_get($item, 'purpose', '-')); ?></td>
                  <td class="px-3 py-3">
                    <?php if(is_string($storeUrl) && Str::startsWith($storeUrl, ['http://', 'https://'])): ?>
                      <a href="<?php echo e($storeUrl); ?>" target="_blank" rel="noopener noreferrer" class="font-medium text-[#4f6ef7] hover:text-[#3d5ce0]"><?php echo e($storeName); ?></a>
                    <?php else: ?>
                      <span class="text-gray-500"><?php echo e($storeName); ?></span>
                    <?php endif; ?>
                  </td>
                  <td class="px-3 py-3"><?php echo e(data_get($item, 'quantity', '-')); ?></td>
                  <td class="px-3 py-3 font-medium"><?php echo e($moneyLabel($price)); ?></td>
                  <td class="max-w-sm px-3 py-3 text-gray-500"><?php echo e(data_get($item, 'notes', data_get($item, 'source_type', '-'))); ?></td>
                </tr>
              <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </tbody>
          </table>
        </div>
        <div class="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
          <?php $__currentLoopData = $shoppingRecommendations; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <?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'));
            ?>
            <article class="overflow-hidden rounded-xl border border-gray-100 bg-gray-50">
              <?php if($productImageUrl): ?>
                <a href="<?php echo e($cardUrl); ?>" target="_blank" rel="noopener noreferrer" class="block bg-white">
                  <img src="<?php echo e($productImageUrl); ?>" alt="<?php echo e($cardItemName); ?>" class="h-44 w-full object-contain p-4" loading="lazy" referrerpolicy="no-referrer">
                </a>
              <?php elseif(is_string($embedUrl) && Str::startsWith($embedUrl, ['http://', 'https://'])): ?>
                <iframe src="<?php echo e($embedUrl); ?>" title="<?php echo e($cardItemName); ?>" class="h-44 w-full bg-white" loading="lazy"></iframe>
              <?php 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"><?php echo e($cardItemName); ?></p>
                    <p class="mt-1 text-xs text-gray-400"><?php echo e(__('Product image is not available yet')); ?></p>
                  </div>
                </div>
              <?php endif; ?>
              <div class="p-3">
                <p class="text-xs font-medium text-gray-400"><?php echo e($cardStore); ?></p>
                <p class="mt-1 text-sm font-semibold"><?php echo e($moneyLabel(data_get($item, 'estimated_total_price', data_get($item, 'estimated_unit_price', '-')))); ?></p>
                <?php if(is_string($cardUrl) && Str::startsWith($cardUrl, ['http://', 'https://'])): ?>
                  <a href="<?php echo e($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]"><?php echo e(__('Open Store Link')); ?></a>
                <?php endif; ?>
              </div>
            </article>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </div>
      <?php endif; ?>
    </div>
  <?php endif; ?>

  <?php 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"><?php echo e(count($groqAnalyses)); ?> model outputs</p>
      </div>
      <div class="grid gap-4 lg:grid-cols-2">
        <?php $__currentLoopData = $groqAnalyses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $analysis): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
          <?php $content = $analysis['content'] ?? []; ?>
          <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"><?php echo e($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"><?php echo e(Str::headline($analysis['kind'] ?? 'analysis')); ?></span>
            </div>
            <?php 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 <?php echo e($analysis['fallback_from']); ?> was rate limited.
              </p>
            <?php endif; ?>
            <p class="text-sm leading-6 text-gray-600"><?php echo e($content['summary'] ?? $analysis['raw_text'] ?? 'Analysis saved.'); ?></p>
            <?php 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">
                  <?php $__currentLoopData = (array) $content['recommended_next_steps']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $step): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <li><?php echo e(is_array($step) ? json_encode($step) : $step); ?></li>
                  <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </ul>
              </div>
            <?php endif; ?>
          </article>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
      </div>
    </div>
  <?php endif; ?>

  <?php 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"><?php echo e(__('Roboflow Visualizations')); ?></h2>
        <p class="text-sm text-gray-400"><?php echo e(count($visualizationImages)); ?> image outputs</p>
      </div>
      <div class="grid gap-4 lg:grid-cols-2">
        <?php $__currentLoopData = $visualizationImages; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $image): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
          <figure class="overflow-hidden rounded-xl border border-gray-100 bg-white">
            <button type="button" onclick="openReportImageModal('<?php echo e(e($image['url'] ?? '')); ?>', '<?php echo e(e($image['key'] ?? 'Visualization')); ?>')" class="block w-full bg-gray-950">
              <img src="<?php echo e($image['url'] ?? ''); ?>" alt="<?php echo e($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"><?php echo e($image['key'] ?? 'Visualization'); ?></span>
              <button type="button" onclick="openReportImageModal('<?php echo e(e($image['url'] ?? '')); ?>', '<?php echo e(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>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
      </div>
    </div>
  <?php endif; ?>

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

  <div class="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
    <h2 class="mb-4 text-base font-semibold"><?php echo e(__('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">
          <?php $__empty_1 = true; $__currentLoopData = $inspection->damageFindings; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $finding): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
            <?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, []);
            ?>
            <tr>
              <td class="px-3 py-3 font-medium"><?php echo e($finding->category); ?></td>
              <td class="px-3 py-3"><span class="rounded-lg px-2 py-1 text-xs font-medium <?php echo e($severityClasses[$finding->severity] ?? 'bg-gray-100 text-gray-600'); ?>"><?php echo e(Str::headline($finding->severity)); ?></span></td>
              <td class="px-3 py-3"><?php echo e(number_format($finding->confidence, 1)); ?>%</td>
              <td class="px-3 py-3">
                <p><?php echo e($moneyLabel($finding->estimated_repair_cost)); ?></p>
                <?php if(data_get($detail, 'material_cost') || data_get($detail, 'labor_cost')): ?>
                  <p class="mt-1 text-xs text-gray-400"><?php echo e(__('Materials')); ?>: <?php echo e($moneyLabel(data_get($detail, 'material_cost', '-'))); ?></p>
                  <p class="text-xs text-gray-400"><?php echo e(__('Labor')); ?>: <?php echo e($moneyLabel(data_get($detail, 'labor_cost', '-'))); ?></p>
                <?php endif; ?>
              </td>
              <td class="max-w-md px-3 py-3 text-gray-500">
                <p><?php echo e(Str::limit($finding->notes, 120)); ?></p>
                <?php if(data_get($detail, 'assumptions')): ?>
                  <p class="mt-1 text-xs text-gray-400"><?php echo e(__('Assumptions')); ?>: <?php echo e(is_array(data_get($detail, 'assumptions')) ? implode('; ', data_get($detail, 'assumptions')) : data_get($detail, 'assumptions')); ?></p>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
            <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>
          <?php endif; ?>
        </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>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('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>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\ariqa\Documents\matkul\smster 4\data sains\prj\homeinspector\resources\views/reports/show.blade.php ENDPATH**/ ?>