@extends('portal.layout')
@section('title', 'Survey Analysis Results')

@section('content')
@php
    $statusColors = ['pending'=>'#f59e0b','processing'=>'#3b82f6','completed'=>'#22c55e','failed'=>'#ef4444'];
    $r = $survey->ai_analysis_raw ?? [];
    $dims = $survey->dimensions_detected ?? [];
@endphp

<div style="max-width:760px;margin:0 auto;padding:32px 16px;">

    {{-- Header --}}
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:28px;flex-wrap:wrap;gap:12px;">
        <div>
            <div style="font-size:12px;color:#64748b;margin-bottom:4px;">
                <a href="{{ route('portal.analyze.form') }}" style="color:#3b82f6;">← Back to Analysis</a>
            </div>
            <h1 style="font-size:20px;font-weight:700;color:#f1f5f9;margin:0;">Survey Analysis Results</h1>
            <div style="font-size:12px;color:#64748b;margin-top:4px;">{{ $survey->original_filename }} · {{ $survey->created_at->diffForHumans() }}</div>
        </div>
        <span style="padding:6px 14px;border-radius:20px;font-size:12px;font-weight:600;background:rgba(34,197,94,.12);color:{{ $statusColors[$survey->ai_status] }};">
            {{ ucfirst($survey->ai_status) }}
        </span>
    </div>

    @if(session('success'))
        <div style="background:rgba(34,197,94,.12);border:1px solid rgba(34,197,94,.3);border-radius:8px;padding:12px 16px;margin-bottom:16px;color:#86efac;font-size:13px;">
            {{ session('success') }}
        </div>
    @endif

    @if($survey->ai_status === 'failed')
    <div style="background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.3);border-radius:8px;padding:16px;margin-bottom:20px;">
        <div style="color:#fca5a5;font-weight:600;margin-bottom:4px;">Analysis Failed</div>
        <div style="color:#94a3b8;font-size:12px;">{{ $survey->ai_error }}</div>
        <form method="POST" action="{{ route('portal.survey.reanalyze', $survey) }}" style="margin-top:12px;">
            @csrf
            <button type="submit" style="background:#ef4444;color:white;border:none;padding:8px 16px;border-radius:6px;font-size:13px;cursor:pointer;">Retry Analysis</button>
        </form>
    </div>
    @endif

    @if($survey->ai_status === 'completed')

    {{-- Key metrics --}}
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-bottom:24px;">
        @php
            $metrics = [
                ['Plot Area', $survey->extracted_area_sqm ? number_format($survey->extracted_area_sqm, 2).' sqm' : '—', '#3b82f6', 'maximize-2'],
                ['Dimensions', ($survey->plot_length_m && $survey->plot_width_m) ? $survey->plot_length_m.'m × '.$survey->plot_width_m.'m' : '—', '#8b5cf6', 'ruler'],
                ['Road Frontage', $survey->road_frontage_m ? $survey->road_frontage_m.'m' : '—', '#10b981', 'road'],
                ['Survey No.', $survey->survey_number ?? '—', '#f59e0b', 'hash'],
                ['Land Use', $survey->land_use_type ? ucfirst($survey->land_use_type) : '—', '#ec4899', 'tag'],
                ['Ownership', $survey->ownership_type ? ucfirst($survey->ownership_type) : '—', '#64748b', 'user'],
            ];
        @endphp
        @foreach($metrics as [$label, $value, $color, $icon])
        <div style="background:#1e293b;border:1px solid #334155;border-radius:10px;padding:14px;">
            <div style="display:flex;align-items:center;gap:6px;margin-bottom:6px;">
                <i data-lucide="{{ $icon }}" style="width:12px;height:12px;color:{{ $color }};"></i>
                <span style="font-size:10px;color:#64748b;text-transform:uppercase;letter-spacing:.5px;">{{ $label }}</span>
            </div>
            <div style="font-size:15px;font-weight:600;color:#f1f5f9;">{{ $value }}</div>
        </div>
        @endforeach
    </div>

    {{-- Location details --}}
    @if($survey->village_name || $survey->taluka_name || $survey->district_name)
    <div style="background:#1e293b;border-radius:10px;padding:16px;margin-bottom:20px;border:1px solid #334155;">
        <div style="font-size:12px;font-weight:600;color:#94a3b8;margin-bottom:10px;">Location Details from Survey</div>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:10px;font-size:13px;">
            @if($survey->village_name)
            <div><span style="color:#64748b;font-size:11px;">Village:</span><br><strong style="color:#f1f5f9;">{{ $survey->village_name }}</strong></div>
            @endif
            @if($survey->taluka_name)
            <div><span style="color:#64748b;font-size:11px;">Taluka:</span><br><strong style="color:#f1f5f9;">{{ $survey->taluka_name }}</strong></div>
            @endif
            @if($survey->district_name)
            <div><span style="color:#64748b;font-size:11px;">District:</span><br><strong style="color:#f1f5f9;">{{ $survey->district_name }}</strong></div>
            @endif
        </div>
    </div>
    @endif

    {{-- Boundary information --}}
    @if(!empty($r['north_boundary']) || !empty($r['south_boundary']))
    <div style="background:#1e293b;border-radius:10px;padding:16px;margin-bottom:20px;border:1px solid #334155;">
        <div style="font-size:12px;font-weight:600;color:#94a3b8;margin-bottom:10px;">Boundaries Extracted</div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;font-size:12px;">
            @foreach(['north'=>'N','south'=>'S','east'=>'E','west'=>'W'] as $dir => $label)
                @if(!empty($r["{$dir}_boundary"]))
                <div style="background:rgba(255,255,255,.04);border-radius:6px;padding:8px;">
                    <span style="font-weight:700;color:#3b82f6;">{{ $label }}</span>
                    <span style="color:#94a3b8;margin-left:6px;">{{ $r["{$dir}_boundary"] }}</span>
                </div>
                @endif
            @endforeach
        </div>
    </div>
    @endif

    {{-- Dimensions detected --}}
    @if(count($dims) > 0)
    <div style="background:#1e293b;border-radius:10px;padding:16px;margin-bottom:20px;border:1px solid #334155;">
        <div style="font-size:12px;font-weight:600;color:#94a3b8;margin-bottom:10px;">All Dimensions Detected</div>
        <div style="display:flex;flex-wrap:wrap;gap:8px;">
            @foreach($dims as $dim)
            <span style="background:rgba(59,130,246,.15);border:1px solid rgba(59,130,246,.3);padding:5px 10px;border-radius:20px;font-size:12px;color:#93c5fd;">
                {{ ucfirst($dim['side'] ?? '') }}: {{ $dim['length_m'] ?? '?' }}m
                @if(!empty($dim['annotation'])) — {{ $dim['annotation'] }}@endif
            </span>
            @endforeach
        </div>
    </div>
    @endif

    {{-- Area confirmation --}}
    <div style="background:#1e293b;border-radius:10px;padding:20px;margin-bottom:20px;border:1px solid #334155;">
        <div style="font-size:13px;font-weight:600;color:#f1f5f9;margin-bottom:4px;">
            @if($survey->area_confirmed)
                ✓ Area Confirmed
            @else
                Confirm Plot Area
            @endif
        </div>
        <p style="font-size:12px;color:#64748b;margin:0 0 14px;">
            AI extracted <strong style="color:#f1f5f9;">{{ number_format($survey->extracted_area_sqm ?? 0, 2) }} sqm</strong>
            ({{ number_format(($survey->extracted_area_sqm ?? 0) / 0.8361, 2) }} sq yd).
            @if(!$survey->area_confirmed) Please verify and correct if needed before proceeding. @endif
        </p>

        @if(!$survey->area_confirmed)
        <form method="POST" action="{{ route('portal.survey.confirm', $survey) }}" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
            @csrf
            <input type="number" name="confirmed_area_sqm" value="{{ $survey->extracted_area_sqm ?? '' }}"
                   step="0.01" min="1"
                   style="background:#0f172a;border:1px solid #334155;color:#f1f5f9;padding:8px 12px;border-radius:6px;font-size:13px;width:180px;"
                   placeholder="Area in sq metres" required>
            <span style="font-size:12px;color:#64748b;">sq metres</span>
            <button type="submit" style="background:#10b981;color:white;border:none;padding:8px 16px;border-radius:6px;font-size:13px;cursor:pointer;">Confirm Area</button>
        </form>
        @else
        <div style="font-size:14px;font-weight:600;color:#34d399;">
            {{ number_format($survey->confirmed_area_sqm ?? $survey->extracted_area_sqm, 2) }} sq metres confirmed
        </div>
        @endif
    </div>

    {{-- CTA --}}
    <div style="display:flex;gap:12px;flex-wrap:wrap;">
        @php
            $analyzeUrl = route('portal.analyze.form', ($survey->feasibility_report_id ? [] : [
                'plot_area' => round($survey->effective_area_sqm ?? 0),
                'survey_id' => $survey->id,
            ]));
        @endphp
        <a href="{{ $analyzeUrl }}" style="background:linear-gradient(135deg,#3b82f6,#8b5cf6);color:white;padding:12px 22px;border-radius:8px;font-size:14px;font-weight:600;text-decoration:none;display:inline-flex;align-items:center;gap:6px;">
            <i data-lucide="trending-up" style="width:16px;height:16px;"></i>
            Run Feasibility Analysis
        </a>
        <form method="POST" action="{{ route('portal.survey.reanalyze', $survey) }}" style="display:inline;">
            @csrf
            <div style="display:flex;gap:8px;align-items:center;">
                <input type="text" name="hints" placeholder="Add hints (e.g. 'area in guntha')" style="background:#0f172a;border:1px solid #334155;color:#f1f5f9;padding:8px 12px;border-radius:6px;font-size:12px;width:220px;">
                <button type="submit" style="background:#1e293b;border:1px solid #334155;color:#94a3b8;padding:8px 14px;border-radius:6px;font-size:12px;cursor:pointer;">Re-analyze</button>
            </div>
        </form>
    </div>

    {{-- Bhulekh link --}}
    @if(!empty($survey->bhulekh_data['portal_url']))
    <div style="margin-top:16px;background:rgba(255,255,255,.03);border-radius:8px;padding:12px 16px;font-size:12px;color:#64748b;">
        <i data-lucide="external-link" style="width:12px;height:12px;margin-right:4px;"></i>
        Verify on official land records portal:
        <a href="{{ $survey->bhulekh_data['portal_url'] }}" target="_blank" rel="noopener" style="color:#3b82f6;margin-left:4px;">{{ $survey->bhulekh_data['portal_url'] }}</a>
    </div>
    @endif

    @endif {{-- ai_status === completed --}}

    {{-- AI confidence badge --}}
    @if(!empty($r['confidence']))
    <div style="margin-top:20px;text-align:center;font-size:11px;color:#475569;">
        AI extraction confidence: <strong style="color:#94a3b8;">{{ round($r['confidence'] * 100) }}%</strong> ·
        Document type: <strong style="color:#94a3b8;">{{ $r['document_type'] ?? 'Unknown' }}</strong>
    </div>
    @endif
</div>
@endsection
