{{-- 내 계약 현황 --}}
<div id="tenant-list-container" class="bg-white rounded-xl shadow-sm p-6" x-data="{
    openScenarioModal(tenantId, type) {
        const url = type === 'sales'
            ? `/sales/scenarios/${tenantId}/sales`
            : `/sales/scenarios/${tenantId}/manager`;
        htmx.ajax('GET', url, {
            target: '#scenario-modal-container',
            swap: 'innerHTML'
        });
    },
    openProspectScenarioModal(prospectId, type, readonly = false) {
        const readonlyParam = readonly ? '?readonly=1' : '';
        const url = type === 'sales'
            ? `/sales/scenarios/prospect/${prospectId}/sales${readonlyParam}`
            : `/sales/scenarios/prospect/${prospectId}/manager${readonlyParam}`;
        htmx.ajax('GET', url, {
            target: '#scenario-modal-container',
            swap: 'innerHTML'
        });
    },
    confirmDeleteTenant(tenantId, companyName) {
        if (confirm(`&quot;${companyName}&quot; 테넌트를 삭제하시겠습니까?\n\n이 작업은 되돌릴 수 없습니다.`)) {
            fetch(`/api/admin/tenants/${tenantId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content
                }
            })
            .then(response => {
                if (response.ok) {
                    const row = document.querySelector(`.tenant-row[data-tenant-id='${tenantId}']`);
                    if (row) row.remove();
                    alert('테넌트가 삭제되었습니다.');
                } else {
                    alert('삭제에 실패했습니다.');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('삭제 중 오류가 발생했습니다.');
            });
        }
    },
}"
@scenario-modal-closed.window="
        document.getElementById('scenario-modal-container').innerHTML = '';
        // 진행률 업데이트
        const detail = $event.detail;
        if (detail && detail.tenantId) {
            updateTenantProgress(detail.tenantId);
        }
        if (detail && detail.prospectId) {
            updateProspectProgress(detail.prospectId);
        }
    ">
    <div class="flex items-center justify-between mb-6">
        <div class="flex items-center gap-3">
            <div class="p-2 bg-blue-100 rounded-lg">
                <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
            </div>
            <h2 class="text-xl font-bold text-gray-800">내 계약 현황</h2>
        </div>
        <span class="text-sm text-gray-500">총 {{ $tenants->total() + (isset($prospects) ? $prospects->count() : 0) }}건</span>
    </div>

    {{-- 가망고객 (아직 전환되지 않은 영업권) --}}
    @if(isset($prospects) && $prospects->isNotEmpty())
        <div class="mb-6">
            <div class="flex items-center gap-2 mb-3">
                <span class="text-sm font-semibold text-orange-600">영업 진행중</span>
                <span class="px-2 py-0.5 bg-orange-100 text-orange-700 text-xs font-medium rounded-full">{{ $prospects->count() }}건</span>
            </div>
            <div class="divide-y divide-gray-100 border border-orange-200 rounded-lg bg-orange-50/30">
                @foreach($prospects as $prospect)
                    @include('sales.dashboard.partials.prospect-row', ['prospect' => $prospect])
                @endforeach
            </div>
        </div>
    @endif

    {{-- 인계 완료 (히스토리) --}}
    @if(isset($handoverProspects) && $handoverProspects->isNotEmpty())
        <div class="mb-6">
            <div class="flex items-center gap-2 mb-3">
                <span class="text-sm font-semibold text-emerald-600">인계 완료</span>
                <span class="px-2 py-0.5 bg-emerald-100 text-emerald-700 text-xs font-medium rounded-full">{{ $handoverProspects->count() }}건</span>
            </div>
            <div class="divide-y divide-gray-100 border border-emerald-200 rounded-lg bg-emerald-50/30">
                @foreach($handoverProspects as $prospect)
                    @php
                        $prospectProgress = \App\Models\Sales\SalesScenarioChecklist::getProspectProgress($prospect->id);
                        $prospectManagement = \App\Models\Sales\SalesTenantManagement::findOrCreateByProspect($prospect->id);

                        // 계약 금액 정보 조회 (management_id 기반)
                        $prospectContractTotals = \App\Models\Sales\SalesContractProduct::where('management_id', $prospectManagement->id)
                            ->selectRaw('SUM(registration_fee) as total_registration_fee, SUM(subscription_fee) as total_subscription_fee, COUNT(*) as product_count')
                            ->first();
                        $prospectTotalRegFee = $prospectContractTotals->total_registration_fee ?? 0;
                        $prospectTotalSubFee = $prospectContractTotals->total_subscription_fee ?? 0;
                        $prospectProductCount = $prospectContractTotals->product_count ?? 0;

                        // 수당 계산 (개인 20%, 단체 30%)
                        $partnerRate = auth()->user()->isGroupPartner() ? 0.30 : 0.20;
                        $partnerCommission = (int)($prospectTotalRegFee * $partnerRate);
                    @endphp
                    <div class="flex items-center gap-4 px-4 py-3 hover:bg-emerald-50 transition-colors" data-prospect-id="{{ $prospect->id }}">
                        <!-- 업체명 및 정보 -->
                        <div class="flex items-center gap-3 flex-shrink-0">
                            <div class="min-w-0">
                                <div class="flex items-center gap-2">
                                    <div class="font-bold text-gray-900 truncate">{{ $prospect->company_name }}</div>
                                    <span class="px-2 py-0.5 text-xs font-medium rounded-full bg-emerald-100 text-emerald-700">
                                        인계완료
                                    </span>
                                </div>
                                <div class="text-xs text-gray-500 mt-0.5">
                                    @if($prospect->ceo_name)
                                        <span>대표: {{ $prospect->ceo_name }}</span>
                                        <span class="mx-1">|</span>
                                    @endif
                                    <span>{{ $prospect->business_number ?? '-' }}</span>
                                </div>
                            </div>
                            {{-- 영업/매니저 기록 조회 버튼 (읽기 전용) --}}
                            <div class="flex-shrink-0 flex items-center gap-1">
                                <button
                                    x-on:click="openProspectScenarioModal({{ $prospect->id }}, 'sales', true)"
                                    class="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-700 hover:bg-blue-200 transition-colors"
                                    title="영업 기록 조회">
                                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                    </svg>
                                    영업
                                </button>
                                <button
                                    x-on:click="openProspectScenarioModal({{ $prospect->id }}, 'manager', true)"
                                    class="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-700 hover:bg-green-200 transition-colors"
                                    title="매니저 기록 조회">
                                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                    </svg>
                                    매니저
                                </button>
                            </div>
                        </div>

                        <!-- 진행 현황 (완료) -->
                        <div class="flex-1 min-w-0 flex items-center gap-4">
                            {{-- 영업/매니저 프로그레스 바 (완료 상태) --}}
                            <div class="flex-1 space-y-1">
                                <div class="flex items-center gap-1">
                                    <span class="text-xs font-medium text-blue-600 w-5 flex-shrink-0">영</span>
                                    <div class="flex-1 bg-blue-500 rounded-full h-1.5 min-w-0"></div>
                                    <span class="text-xs text-gray-500 w-8 text-right flex-shrink-0">100%</span>
                                </div>
                                <div class="flex items-center gap-1">
                                    <span class="text-xs font-medium text-green-600 w-5 flex-shrink-0">매</span>
                                    <div class="flex-1 bg-green-500 rounded-full h-1.5 min-w-0"></div>
                                    <span class="text-xs text-gray-500 w-8 text-right flex-shrink-0">100%</span>
                                </div>
                            </div>

                            {{-- 구분선 --}}
                            <div class="w-px h-8 bg-gray-200 flex-shrink-0"></div>

                            {{-- 개발 완료 표시 --}}
                            <div class="flex-1 min-w-0">
                                <div class="flex items-center gap-3">
                                    <div class="flex-1 min-w-0">
                                        <div class="flex items-center gap-0.5">
                                            @for($i = 0; $i < 8; $i++)
                                            <div class="flex-1 h-2.5 rounded-sm bg-emerald-500"></div>
                                            @endfor
                                        </div>
                                    </div>
                                    <span class="flex-shrink-0 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-emerald-100 text-emerald-700">
                                        <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                                        </svg>
                                        완료
                                    </span>
                                </div>
                            </div>
                        </div>

                        <!-- 계약 금액 정보 -->
                        <div class="flex-shrink-0 text-right border-l border-gray-200 pl-4">
                            @if($prospectProductCount > 0)
                                <div class="space-y-0.5">
                                    <div>
                                        <p class="text-xs text-gray-400">개발비</p>
                                        <p class="text-sm font-bold text-indigo-600">₩{{ number_format($prospectTotalRegFee) }}</p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-gray-400">월 구독료</p>
                                        <p class="text-sm font-bold text-green-600">₩{{ number_format($prospectTotalSubFee) }}</p>
                                    </div>
                                </div>
                            @endif
                        </div>

                        <!-- 수당 정보 -->
                        <div class="flex-shrink-0 text-right border-l border-gray-200 pl-4">
                            <div class="space-y-0.5">
                                <p class="text-xs text-gray-400">예상 수당</p>
                                <p class="text-sm font-bold text-emerald-600">₩{{ number_format($partnerCommission) }}</p>
                            </div>
                        </div>

                        <!-- 완료일 -->
                        <div class="flex-shrink-0 text-center border-l border-gray-200 pl-4">
                            <div class="text-xs text-gray-400">인계일</div>
                            <div class="text-sm font-medium text-gray-600">{{ $prospectManagement->updated_at->format('m/d') }}</div>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>
    @endif

    {{-- 계약 완료 고객 --}}
    @if($tenants->isNotEmpty())
        <div class="flex items-center gap-2 mb-3">
            <span class="text-sm font-semibold text-green-600">계약 완료</span>
            <span class="px-2 py-0.5 bg-green-100 text-green-700 text-xs font-medium rounded-full">{{ $tenants->total() }}건</span>
        </div>
    @endif

    @if($tenants->isEmpty() && (!isset($prospects) || $prospects->isEmpty()))
        <div class="text-center py-16">
            <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
            </div>
            <p class="text-gray-600 font-medium mb-1">등록된 고객이 없습니다</p>
            <p class="text-sm text-gray-400">고객 관리에서 명함을 등록하면 여기에 표시됩니다</p>
        </div>
    @elseif($tenants->isNotEmpty())
        <!-- 테이블 헤더 (숨김 처리 - 심플 레이아웃) -->
        {{-- 헤더 없는 깔끔한 리스트 스타일 --}}

        <!-- 테넌트 목록 -->
        <div class="divide-y divide-gray-100">
            @foreach($tenants as $tenant)
                @php
                    $progress = \App\Models\Sales\SalesScenarioChecklist::getTenantProgress($tenant->id);
                    $management = \App\Models\Sales\SalesTenantManagement::findOrCreateByTenant($tenant->id);
                    $hqStatuses = \App\Models\Sales\SalesTenantManagement::$hqStatusLabels;
                    $hqStatusOrder = \App\Models\Sales\SalesTenantManagement::$hqStatusOrder;
                    $currentHqStep = $hqStatusOrder[$management->hq_status ?? 'pending'] ?? 0;
                    $isHqEnabled = $progress['manager']['percentage'] >= 100;

                    // 계약 금액 정보 조회 (management_id 기반)
                    $contractTotals = \App\Models\Sales\SalesContractProduct::where('management_id', $management->id)
                        ->selectRaw('SUM(registration_fee) as total_registration_fee, SUM(subscription_fee) as total_subscription_fee, COUNT(*) as product_count')
                        ->first();
                    $totalRegFee = $contractTotals->total_registration_fee ?? 0;
                    $totalSubFee = $contractTotals->total_subscription_fee ?? 0;
                    $productCount = $contractTotals->product_count ?? 0;

                    // 현재 사용자의 역할 확인 (tenant 기준 - registered_by는 연결된 prospect에서 확인)
                    $currentUserId = auth()->id();
                    // 테넌트와 연결된 prospect 조회
                    $linkedProspect = \App\Models\Sales\TenantProspect::where('tenant_id', $tenant->id)->first();
                    $tenantIsRegistrar = $linkedProspect && $linkedProspect->registered_by === $currentUserId;
                    $tenantIsManager = $management->manager_user_id === $currentUserId;
                    $tenantHasDifferentManager = $management->manager_user_id && $management->manager_user_id !== $currentUserId;

                    // 버튼 표시 여부
                    $tenantShowSalesButton = $tenantIsRegistrar;
                    $tenantShowManagerButton = $tenantIsManager || (!$tenantHasDifferentManager && $tenantIsRegistrar);
                    $tenantShowManagerProgress = $tenantShowManagerButton;
                @endphp
                <div class="tenant-row" data-tenant-id="{{ $tenant->id }}">
                    <!-- 메인 행 -->
                    <div class="flex items-center gap-4 px-4 py-3 hover:bg-gray-50 transition-colors">
                        <!-- 업체명 + 관리 드롭다운 + 영업/매니저 버튼 (왼쪽 고정) -->
                        <div class="flex items-center gap-3 flex-shrink-0">
                            <div class="min-w-0">
                                <div class="font-bold text-gray-900 truncate">{{ $tenant->company_name }}</div>
                                <div class="text-xs text-gray-500">
                                    @if($tenant->ceo_name)
                                        <span>대표: {{ $tenant->ceo_name }}</span>
                                        <span class="mx-1">|</span>
                                    @endif
                                    <span>{{ $tenant->business_number ?? '-' }}</span>
                                </div>
                            </div>
                            {{-- 담당자 드롭다운 --}}
                            <div class="flex-shrink-0">
                                @include('sales.dashboard.partials.manager-dropdown', ['tenant' => $tenant])
                            </div>
                            {{-- 영업/매니저 진행 버튼 --}}
                            <div class="flex-shrink-0 flex items-center gap-1">
                                @if($tenantShowSalesButton)
                                <button
                                    x-on:click="openScenarioModal({{ $tenant->id }}, 'sales')"
                                    class="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-blue-600 text-white hover:bg-blue-700 transition-colors"
                                    title="영업 시나리오">
                                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7l5 5m0 0l-5 5m5-5H6" />
                                    </svg>
                                    영업
                                </button>
                                @endif
                                @if($tenantShowManagerButton)
                                <button
                                    x-on:click="openScenarioModal({{ $tenant->id }}, 'manager')"
                                    class="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-green-600 text-white hover:bg-green-700 transition-colors"
                                    title="매니저 시나리오">
                                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                    </svg>
                                    매니저
                                </button>
                                @endif
                            </div>
                        </div>

                        <!-- 진행 현황 (영업/매니저 | 개발 진행) -->
                        <div class="flex-1 min-w-0 flex items-center gap-4" id="progress-{{ $tenant->id }}">
                            {{-- 좌측: 영업/매니저 프로그레스 바 --}}
                            <div class="flex-1 space-y-1">
                                {{-- 영업 (등록자에게만 표시) --}}
                                @if($tenantShowSalesButton)
                                <div class="flex items-center gap-1" title="영업 {{ $progress['sales']['percentage'] }}%">
                                    <span class="text-xs font-medium text-blue-600 w-5 flex-shrink-0">영</span>
                                    <div class="flex-1 bg-gray-200 rounded-full h-1.5 min-w-0">
                                        <div class="bg-blue-500 h-1.5 rounded-full transition-all" id="sales-bar-{{ $tenant->id }}" style="width: {{ $progress['sales']['percentage'] }}%"></div>
                                    </div>
                                    <span class="text-xs text-gray-500 w-8 text-right flex-shrink-0" id="sales-pct-{{ $tenant->id }}">{{ $progress['sales']['percentage'] }}%</span>
                                </div>
                                @endif
                                {{-- 매니저 (매니저에게만 표시) --}}
                                @if($tenantShowManagerProgress)
                                <div class="flex items-center gap-1" title="매니저 {{ $progress['manager']['percentage'] }}%">
                                    <span class="text-xs font-medium text-green-600 w-5 flex-shrink-0">매</span>
                                    <div class="flex-1 bg-gray-200 rounded-full h-1.5 min-w-0">
                                        <div class="bg-green-500 h-1.5 rounded-full transition-all" id="manager-bar-{{ $tenant->id }}" style="width: {{ $progress['manager']['percentage'] }}%"></div>
                                    </div>
                                    <span class="text-xs text-gray-500 w-8 text-right flex-shrink-0" id="manager-pct-{{ $tenant->id }}">{{ $progress['manager']['percentage'] }}%</span>
                                </div>
                                @endif
                            </div>

                            {{-- 구분선 --}}
                            <div class="w-px h-8 bg-gray-200 flex-shrink-0"></div>

                            {{-- 우측: 개발 진행 상태 (7단계 + 상태 배지) --}}
                            <div class="flex-1 min-w-0">
                                @if($isHqEnabled)
                                    <div class="flex items-center gap-3">
                                        {{-- 7단계 프로그래스 바 --}}
                                        <div class="flex-1 min-w-0">
                                            <div class="flex items-center gap-0.5">
                                                @foreach($hqStatuses as $statusKey => $statusLabel)
                                                    @php
                                                        $stepNum = $hqStatusOrder[$statusKey];
                                                        $isCompleted = $stepNum < $currentHqStep;
                                                        $isCurrent = $stepNum === $currentHqStep;
                                                    @endphp
                                                    <div class="group relative flex-1">
                                                        <div class="h-2.5 rounded-sm transition-all {{ $isCompleted ? 'bg-purple-500' : ($isCurrent ? 'bg-purple-400 animate-pulse' : 'bg-gray-200') }}"></div>
                                                        <div class="absolute bottom-full left-1/2 -translate-x-1/2 mb-1 px-2 py-1 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-10 pointer-events-none">
                                                            {{ $stepNum + 1 }}. {{ $statusLabel }}
                                                        </div>
                                                    </div>
                                                @endforeach
                                            </div>
                                        </div>
                                        {{-- 현재 상태 배지 --}}
                                        <span class="flex-shrink-0 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium
                                            @if($management->hq_status === 'handover') bg-emerald-100 text-emerald-700
                                            @elseif(in_array($management->hq_status, ['coding', 'dev_test', 'dev_done'])) bg-purple-100 text-purple-700
                                            @elseif(in_array($management->hq_status, ['review', 'planning'])) bg-blue-100 text-blue-700
                                            @elseif($management->hq_status === 'int_test') bg-orange-100 text-orange-700
                                            @else bg-gray-100 text-gray-600 @endif">
                                            {{ $management->hq_status_label }}
                                        </span>
                                    </div>
                                @else
                                    <div class="flex items-center gap-3">
                                        {{-- 비활성 프로그래스 바 --}}
                                        <div class="flex-1 min-w-0">
                                            <div class="flex items-center gap-0.5">
                                                @foreach($hqStatuses as $statusKey => $statusLabel)
                                                    <div class="group relative flex-1">
                                                        <div class="h-2.5 rounded-sm bg-gray-100"></div>
                                                        <div class="absolute bottom-full left-1/2 -translate-x-1/2 mb-1 px-2 py-1 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-10 pointer-events-none">
                                                            {{ $hqStatusOrder[$statusKey] + 1 }}. {{ $statusLabel }}
                                                        </div>
                                                    </div>
                                                @endforeach
                                            </div>
                                        </div>
                                        {{-- 대기 배지 --}}
                                        <span class="flex-shrink-0 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-400">
                                            영업/매니저 완료 후 시작
                                        </span>
                                    </div>
                                @endif
                            </div>
                        </div>

                        <!-- 계약 금액 정보 (오른쪽 세로 배치) -->
                        <div class="flex-shrink-0 text-right border-l border-gray-200 pl-6">
                            @if($productCount > 0)
                                <div class="space-y-1">
                                    <div>
                                        <p class="text-xs text-gray-400">개발비</p>
                                        <p class="text-lg font-bold text-indigo-600">₩{{ number_format($totalRegFee) }}</p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-gray-400">월 구독료</p>
                                        <p class="text-lg font-bold text-green-600">₩{{ number_format($totalSubFee) }}</p>
                                    </div>
                                </div>
                            @else
                                <div class="space-y-1">
                                    <div>
                                        <p class="text-xs text-gray-400">개발비</p>
                                        <p class="text-lg font-bold text-gray-300">-</p>
                                    </div>
                                    <div>
                                        <p class="text-xs text-gray-400">월 구독료</p>
                                        <p class="text-lg font-bold text-gray-300">-</p>
                                    </div>
                                </div>
                            @endif
                        </div>
                    </div>

                </div>
            @endforeach
        </div>

        {{-- 페이지네이션 --}}
        @if($tenants->hasPages())
        <div class="mt-6 flex items-center justify-between border-t border-gray-200 pt-4">
            <div class="text-sm text-gray-500">
                {{ $tenants->firstItem() }} - {{ $tenants->lastItem() }} / 총 {{ $tenants->total() }}건
            </div>
            <div class="flex items-center gap-1">
                {{-- 이전 페이지 --}}
                @if($tenants->onFirstPage())
                    <span class="px-3 py-2 text-sm text-gray-300 cursor-not-allowed">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                        </svg>
                    </span>
                @else
                    <button type="button"
                        hx-get="{{ $tenants->previousPageUrl() }}"
                        hx-target="#dashboard-data"
                        hx-swap="innerHTML"
                        hx-indicator="#loading-indicator"
                        class="px-3 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                        </svg>
                    </button>
                @endif

                {{-- 페이지 번호 --}}
                @foreach($tenants->getUrlRange(max(1, $tenants->currentPage() - 2), min($tenants->lastPage(), $tenants->currentPage() + 2)) as $page => $url)
                    @if($page == $tenants->currentPage())
                        <span class="px-3 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg">{{ $page }}</span>
                    @else
                        <button type="button"
                            hx-get="{{ $url }}"
                            hx-target="#dashboard-data"
                            hx-swap="innerHTML"
                            hx-indicator="#loading-indicator"
                            class="px-3 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
                            {{ $page }}
                        </button>
                    @endif
                @endforeach

                {{-- 다음 페이지 --}}
                @if($tenants->hasMorePages())
                    <button type="button"
                        hx-get="{{ $tenants->nextPageUrl() }}"
                        hx-target="#dashboard-data"
                        hx-swap="innerHTML"
                        hx-indicator="#loading-indicator"
                        class="px-3 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                        </svg>
                    </button>
                @else
                    <span class="px-3 py-2 text-sm text-gray-300 cursor-not-allowed">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                        </svg>
                    </span>
                @endif
            </div>
        </div>
        @endif
    @endif

    {{-- 시나리오 모달 컨테이너 --}}
    <div id="scenario-modal-container"></div>
</div>

<script>
// 테넌트 진행률 업데이트 함수
async function updateTenantProgress(tenantId) {
    try {
        // 영업 진행률 조회
        const salesRes = await fetch(`/sales/scenarios/${tenantId}/sales/progress`, {
            headers: { 'Accept': 'application/json' }
        });
        const salesData = await salesRes.json();

        // 매니저 진행률 조회
        const managerRes = await fetch(`/sales/scenarios/${tenantId}/manager/progress`, {
            headers: { 'Accept': 'application/json' }
        });
        const managerData = await managerRes.json();

        // DOM 업데이트 - 영업
        const salesPct = document.getElementById(`sales-pct-${tenantId}`);
        const salesBar = document.getElementById(`sales-bar-${tenantId}`);
        if (salesPct && salesBar && salesData.progress) {
            salesPct.textContent = `${salesData.progress.percentage}%`;
            salesBar.style.width = `${salesData.progress.percentage}%`;
        }

        // DOM 업데이트 - 매니저
        const managerPct = document.getElementById(`manager-pct-${tenantId}`);
        const managerBar = document.getElementById(`manager-bar-${tenantId}`);
        if (managerPct && managerBar && managerData.progress) {
            managerPct.textContent = `${managerData.progress.percentage}%`;
            managerBar.style.width = `${managerData.progress.percentage}%`;
        }
    } catch (error) {
        console.error('진행률 업데이트 실패:', error);
    }
}

// 가망고객 진행률 업데이트 함수
async function updateProspectProgress(prospectId) {
    try {
        // 영업 진행률 조회
        const salesRes = await fetch(`/sales/scenarios/prospect/${prospectId}/sales/progress`, {
            headers: { 'Accept': 'application/json' }
        });
        const salesData = await salesRes.json();

        // 매니저 진행률 조회
        const managerRes = await fetch(`/sales/scenarios/prospect/${prospectId}/manager/progress`, {
            headers: { 'Accept': 'application/json' }
        });
        const managerData = await managerRes.json();

        // DOM 업데이트 - 영업
        const salesPct = document.getElementById(`prospect-sales-pct-${prospectId}`);
        const salesBar = document.getElementById(`prospect-sales-bar-${prospectId}`);
        if (salesPct && salesBar && salesData.progress) {
            salesPct.textContent = `${salesData.progress.percentage}%`;
            salesBar.style.width = `${salesData.progress.percentage}%`;
        }

        // DOM 업데이트 - 매니저
        const managerPct = document.getElementById(`prospect-manager-pct-${prospectId}`);
        const managerBar = document.getElementById(`prospect-manager-bar-${prospectId}`);
        if (managerPct && managerBar && managerData.progress) {
            managerPct.textContent = `${managerData.progress.percentage}%`;
            managerBar.style.width = `${managerData.progress.percentage}%`;
        }
    } catch (error) {
        console.error('가망고객 진행률 업데이트 실패:', error);
    }
}
</script>
