@php
    use App\Enums\CampaignStatus;
    $statusLabel = CampaignStatus::tryFrom($campaign->status)?->label() ?? $campaign->status;
    $statusClass = CampaignStatus::tryFrom($campaign->status)?->cssClass() ?? 'status-badge--draft';

    $initialData = [
        'campaignId' => $campaignId,
        'campaignName' => $campaign->campaign_name,
        'productName' => $campaign->product_name ?? '',
        'ownerName' => $campaign->relationLoaded('assignedTo') && $campaign->assignedTo
            ? ($campaign->assignedTo->display_name ?? $campaign->assignedTo->name ?? '') : '',
        'status' => $campaign->status,
        'startDate' => $campaign->start_date ? $campaign->start_date->toDateString() : '',
        'endDate' => $campaign->end_date ? $campaign->end_date->toDateString() : '',
        'notes' => $campaign->notes ?? '',
        'users' => $users,
        // [TỐI ƯU] Inject pre-computed data để Alpine không cần gọi detailJson() API
        '_initialKocs' => $_initialKocs ?? [],
        '_initialStats' => $_initialStats ?? [
            'not_contacted' => 0, 'pending' => 0, 'not_approved' => 0,
            'negotiating' => 0, 'confirmed' => 0, 'completed' => 0,
            'castCost' => 0, 'sampleCost' => 0, 'shippingCost' => 0, 'totalCost' => 0,
        ],
    ];
@endphp

@extends('layouts.app')

@section('content')
<div id="campaign-detail-page"
     x-data='campaignDetailPage(@json($initialData))'
     x-init="init()"
     data-can-export="{{ $can_export ? '1' : '0' }}"
     data-can-export-pdf="{{ $can_export_pdf ? '1' : '0' }}">

    <x-layout.page-header
        title="Chi Tiết Chiến Dịch"
        iconFa="bullseye"
        :back="['href' => route('campaigns'), 'label' => 'Quay lại', 'icon' => '‹']"
    >
        <x-slot name="meta">
            <div class="cd-header-meta">
                <div class="cd-header-info-group">
                    <span class="cd-header-campaign" x-text="campaignName">—</span>
                    <span class="cd-header-sep">·</span>
                    <span class="cd-header-product" x-text="productName || '—'">—</span>
                </div>
                <div class="cd-header-status-group">
                    <span class="status-badge {{ $statusClass }}" x-text="statusLabel"></span>
                </div>
            </div>
        </x-slot>
    </x-layout.page-header>

    <div class="list-page-content">

        <x-ui.cards type="section-card">
            <div class="detail-grid">
                <div>
                    <span class="detail-label">Tổng KOC</span>
                    <p class="detail-value detail-value--lg" id="total-kocs" x-text="totalKocs">0</p>
                </div>
                <div>
                    <span class="detail-label">Người phụ trách</span>
                    <p class="detail-value" x-text="ownerName || '—'">—</p>
                </div>
                <div>
                    <span class="detail-label">Ngày bắt đầu</span>
                    <p class="detail-value" x-text="startDate ? formatDate(startDate) : '—'">—</p>
                </div>
                <div>
                    <span class="detail-label">Ngày kết thúc</span>
                    <p class="detail-value" x-text="endDate ? formatDate(endDate) : '—'">—</p>
                </div>
            </div>
        </x-ui.cards>

        {{-- KOC Status Metrics --}}
        <div class="section-metrics">
            <p class="stat-section-label">Trạng thái KOC</p>
            <div class="stat-grid stat-grid--six">
                <x-ui.cards type="stat-card" label="Chưa duyệt" icon="👥">
                    <span x-text="stats.not_contacted">0</span>
                </x-ui.cards>
                <x-ui.cards type="stat-card" label="Đã duyệt" icon="📞">
                    <span x-text="stats.pending">0</span>
                </x-ui.cards>
                <x-ui.cards type="stat-card" label="Không duyệt" icon="❌">
                    <span x-text="stats.not_approved">0</span>
                </x-ui.cards>
                <x-ui.cards type="stat-card" label="Đang deal" icon="💬">
                    <span x-text="stats.negotiating">0</span>
                </x-ui.cards>
                <x-ui.cards type="stat-card" label="Đã chốt" icon="✅">
                    <span x-text="stats.confirmed">0</span>
                </x-ui.cards>
                <x-ui.cards type="stat-card" label="Đã gửi hàng" icon="📦">
                    <span x-text="stats.completed">0</span>
                </x-ui.cards>
            </div>
        </div>

        {{-- Cost Metrics --}}
        <div class="section-metrics">
            <p class="stat-section-label">Chi phí chiến dịch</p>
            <div class="stat-grid stat-grid--four">
                <x-ui.cards type="stat-card" label="Chi phí cast" icon="💵">
                    <span x-text="formatCurrency(stats.castCost) + ' VND'">0 VND</span>
                </x-ui.cards>
                <x-ui.cards type="stat-card" label="Chi phí mẫu" icon="🎁">
                    <span x-text="formatCurrency(stats.sampleCost) + ' VND'">0 VND</span>
                </x-ui.cards>
                <x-ui.cards type="stat-card" label="Chi phí ship" icon="🚚">
                    <span x-text="formatCurrency(stats.shippingCost) + ' VND'">0 VND</span>
                </x-ui.cards>
                <x-ui.cards type="stat-card" label="Tổng 3 chi phí" icon="💰" class="c-indigo">
                    <span x-text="formatCurrency(stats.totalCost) + ' VND'">0 VND</span>
                </x-ui.cards>
            </div>
        </div>

        {{-- Booking Section: Tabs + Tables --}}
        @php
            // Columns chung cho cả 2 tab
            $commonColumns = [
                ['key' => '_stt', 'label' => 'STT', 'type' => 'index', 'cellClass' => 'col-center', 'widthClass' => 'col-xxs', 'truncate' => false, 'toggleable' => false],
                ['key' => 'creator_name', 'label' => 'Tên KOC', 'toggleable' => false, 'render' => 'renderKocName(row)', 'cellClass' => 'col-left', 'widthClass' => 'col-name', 'sticky' => 'left'],
                ['key' => 'links', 'label' => 'Link', 'render' => 'window.buildSocialLinksHtml(row.koc || row)', 'cellClass' => 'col-left', 'widthClass' => 'col-link', 'truncate' => false],
                ['key' => 'contact', 'label' => 'Liên hệ', 'render' => 'window.buildContactButtonHtml(row.koc || row)', 'cellClass' => 'col-center', 'widthClass' => 'col-sm', 'truncate' => false],
                ['key' => 'owner', 'label' => 'Phụ trách', 'render' => 'renderOwnerName(row)', 'cellClass' => 'col-left', 'widthClass' => 'col-sm'],
                ['key' => 'created_at', 'label' => 'Tham gia', 'type' => 'date', 'cellClass' => 'col-center', 'widthClass' => 'col-sm'],
                ['key' => 'engagement_natural', 'label' => '% AFF TN', 'render' => 'formatDecimal(row.engagement_natural)', 'cellClass' => 'col-right number-cell', 'widthClass' => 'col-sm', 'truncate' => false],
                ['key' => 'engagement_ads', 'label' => '% AFF Ads', 'render' => 'formatDecimal(row.engagement_ads)', 'cellClass' => 'col-right number-cell', 'widthClass' => 'col-sm', 'truncate' => false],
                ['key' => 'quote', 'label' => 'Báo giá', 'type' => 'currency', 'cellClass' => 'col-right number-cell', 'widthClass' => 'col-sm', 'truncate' => false],
                ['key' => 'cast_cost', 'label' => '💲 Cast', 'type' => 'currency', 'cellClass' => 'col-right number-cell', 'widthClass' => 'col-sm', 'truncate' => false],
                ['key' => 'sample_cost', 'label' => '💲 Mẫu', 'type' => 'currency', 'cellClass' => 'col-right number-cell', 'widthClass' => 'col-sm', 'truncate' => false],
                ['key' => 'shipping_cost', 'label' => '💲 Ship', 'type' => 'currency', 'cellClass' => 'col-right number-cell', 'widthClass' => 'col-sm', 'truncate' => false],
                ['key' => 'order_code', 'label' => 'Mã đơn hàng', 'cellClass' => 'col-left', 'widthClass' => 'col-md'],
                ['key' => 'send_date', 'label' => 'Ngày gửi SP', 'type' => 'date', 'cellClass' => 'col-center', 'widthClass' => 'col-sm'],
                ['key' => 'eta_date', 'label' => 'Dự nhận', 'type' => 'date', 'cellClass' => 'col-center', 'widthClass' => 'col-sm'],
                ['key' => 'status', 'label' => 'Trạng thái', 'render' => 'renderStatusDropdown(row)', 'cellClass' => 'col-center col-status', 'widthClass' => 'col-sm', 'truncate' => false],
            ];

            // Columns riêng cho Video
            $videoColumns = [
                ['key' => 'air_date', 'label' => 'Chốt air vid', 'type' => 'date', 'cellClass' => 'col-center col-air-date', 'widthClass' => 'col-sm'],
                ['key' => 'video_links', 'label' => 'Video', 'render' => 'renderVideoProgress(row)', 'cellClass' => 'col-center col-video-links', 'widthClass' => 'col-sm', 'truncate' => false],
                ['key' => 'notes', 'label' => 'Ghi chú', 'render' => 'window.renderNotesBadgeHtml(row)', 'cellClass' => 'col-center', 'widthClass' => 'col-sm', 'truncate' => false],
            ];

            // Columns riêng cho Livestream
            $livestreamColumns = [
                ['key' => 'sample_type', 'label' => 'Phân loại mẫu', 'cellClass' => 'col-left col-sample-type', 'widthClass' => 'col-md'],
                ['key' => 'deal_live_registration', 'label' => 'Đăng ký deal live', 'cellClass' => 'col-left col-deal-live', 'widthClass' => 'col-md'],
                ['key' => 'notes', 'label' => 'Ghi chú', 'render' => 'window.renderNotesBadgeHtml(row)', 'cellClass' => 'col-center', 'widthClass' => 'col-sm', 'truncate' => false],
            ];

            // Toggleable columns riêng
            $videoToggleable = [
                ['key' => 'links', 'label' => 'Link'], ['key' => 'contact', 'label' => 'Liên hệ'],
                ['key' => 'owner', 'label' => 'Phụ trách'], ['key' => 'created_at', 'label' => 'Tham gia'],
                ['key' => 'engagement_natural', 'label' => '% AFF TN'], ['key' => 'engagement_ads', 'label' => '% AFF Ads'],
                ['key' => 'quote', 'label' => 'Báo giá'], ['key' => 'cast_cost', 'label' => 'Chi phí cast'],
                ['key' => 'sample_cost', 'label' => 'Chi phí mẫu'], ['key' => 'shipping_cost', 'label' => 'Chi phí ship'],
                ['key' => 'order_code', 'label' => 'Mã đơn hàng'], ['key' => 'send_date', 'label' => 'Ngày gửi SP'],
                ['key' => 'eta_date', 'label' => 'Dự nhận'], ['key' => 'air_date', 'label' => 'Chốt air vid'],
                ['key' => 'video_links', 'label' => 'Video'], ['key' => 'status', 'label' => 'Trạng thái'],
                ['key' => 'notes', 'label' => 'Ghi chú'],
            ];

            $livestreamToggleable = [
                ['key' => 'links', 'label' => 'Link'], ['key' => 'contact', 'label' => 'Liên hệ'],
                ['key' => 'owner', 'label' => 'Phụ trách'], ['key' => 'created_at', 'label' => 'Tham gia'],
                ['key' => 'engagement_natural', 'label' => '% AFF TN'], ['key' => 'engagement_ads', 'label' => '% AFF Ads'],
                ['key' => 'quote', 'label' => 'Báo giá'], ['key' => 'cast_cost', 'label' => 'Chi phí cast'],
                ['key' => 'sample_cost', 'label' => 'Chi phí mẫu'], ['key' => 'shipping_cost', 'label' => 'Chi phí ship'],
                ['key' => 'order_code', 'label' => 'Mã đơn hàng'], ['key' => 'send_date', 'label' => 'Ngày gửi SP'],
                ['key' => 'eta_date', 'label' => 'Dự nhận'], ['key' => 'sample_type', 'label' => 'Phân loại mẫu'],
                ['key' => 'deal_live_registration', 'label' => 'Đăng ký deal live'], ['key' => 'status', 'label' => 'Trạng thái'],
                ['key' => 'notes', 'label' => 'Ghi chú'],
            ];
        @endphp

        <div class="booking-section-wrapper">
            {{-- Tabs --}}
            <div class="booking-tabs-wrapper">
                <div class="booking-tabs">
                    <button class="booking-tab-btn" :class="{ active: activeTab === 'video' }" @click="switchTab('video')">
                        <span class="tab-icon">@svg('fas-video')</span>
                        <span class="tab-label">Video</span>
                        <span class="tab-count" x-text="allKocs.filter(k => (k.type||'video') === 'video').length"></span>
                    </button>
                    <button class="booking-tab-btn" :class="{ active: activeTab === 'livestream' }" @click="switchTab('livestream')">
                        <span class="tab-icon">@svg('fas-microphone')</span>
                        <span class="tab-label">Livestream</span>
                        <span class="tab-count" x-text="allKocs.filter(k => (k.type||'video') === 'livestream').length"></span>
                    </button>
                </div>
            </div>

            {{-- Video Tab --}}
            <div x-show="activeTab === 'video'" x-cloak
                 x-data="columnVisibility({ columns: {{ Illuminate\Support\Js::from($videoToggleable) }} })">
                @php $videoAllColumns = array_merge($commonColumns, $videoColumns); @endphp
                <x-ui.cards type="section-card" title="KOC Video" cardClass="list-page-card list-page-table-card">
                    <x-slot name="header">
                        <div class="section-header-actions">
                            <x-ui.buttons type="toolbar-button" variant="secondary" iconFa="plus" label="Thêm KOC" @click="handleOpenPickerKocs()" />
                            <x-ui.buttons type="toolbar-button" variant="ghost" iconFa="file-export" label="Xuất Excel" @click="handleExportCampaign()" x-bind:disabled="!canExport" />
                            <select x-model="filterStatus" @change="applyFilters()" class="filter-select">
                                <option value="">Tất cả trạng thái</option>
                                @foreach (\App\Enums\BookingStatus::kocOptions() as $option)
                                    <option value="{{ $option['value'] }}">{{ $option['label'] }}</option>
                                @endforeach
                            </select>
                            <select x-model="filterOwner" @change="applyFilters()" class="filter-select">
                                <option value="">Tất cả người phụ trách</option>
                                <template x-for="(name, id) in ownerMap" :key="id">
                                    <option :value="id" x-text="name"></option>
                                </template>
                            </select>
                        </div>
                        <x-ui.column-visibility />
                    </x-slot>
                    <x-ui.tabular
                        id="kocs-table-video"
                        :columns="$videoAllColumns"
                        column-visibility="visible"
                        rows="paginatedKocs"
                        loading="loading"
                        loadingText="Đang tải..."
                        emptyText="Không có KOC Video"
                        :sortable="false"
                        hasActions="true"
                    >
                        <x-slot name="actions">
                            <button class="btn-icon" title="Sửa" @click="handleEditKOC(row)" type="button">✏️</button>
                            <button class="btn-icon" title="Xóa" @click="handleDeleteKOC(row)" type="button">🗑️</button>
                        </x-slot>
                    </x-ui.tabular>
                    <x-ui.pagination id="campaign-kocs-pagination-video" page="currentPage" onPageSizeChange="pageSizeChange" />
                </x-ui.cards>
                {{-- Video Editor only for video tab --}}
                <div x-show="expandedKocId" x-cloak class="video-editor-section" x-html="renderVideoEditorHtml()" id="video-editor-container"></div>
            </div>

            {{-- Livestream Tab --}}
            <div x-show="activeTab === 'livestream'" x-cloak
                 x-data="columnVisibility({ columns: {{ Illuminate\Support\Js::from($livestreamToggleable) }} })">
                @php $liveAllColumns = array_merge($commonColumns, $livestreamColumns); @endphp
                <x-ui.cards type="section-card" title="KOC Livestream" cardClass="list-page-card list-page-table-card">
                    <x-slot name="header">
                        <div class="section-header-actions">
                            <x-ui.buttons type="toolbar-button" variant="secondary" iconFa="plus" label="Thêm KOC" @click="handleOpenPickerKocs()" />
                            <x-ui.buttons type="toolbar-button" variant="ghost" iconFa="file-export" label="Xuất Excel" @click="handleExportCampaign()" x-bind:disabled="!canExport" />
                            <select x-model="filterStatus" @change="applyFilters()" class="filter-select">
                                <option value="">Tất cả trạng thái</option>
                                @foreach (\App\Enums\BookingStatus::kocOptions() as $option)
                                    <option value="{{ $option['value'] }}">{{ $option['label'] }}</option>
                                @endforeach
                            </select>
                            <select x-model="filterOwner" @change="applyFilters()" class="filter-select">
                                <option value="">Tất cả người phụ trách</option>
                                <template x-for="(name, id) in ownerMap" :key="id">
                                    <option :value="id" x-text="name"></option>
                                </template>
                            </select>
                        </div>
                        <x-ui.column-visibility />
                    </x-slot>
                    <x-ui.tabular
                        id="kocs-table-livestream"
                        :columns="$liveAllColumns"
                        column-visibility="visible"
                        rows="paginatedKocs"
                        loading="loading"
                        loadingText="Đang tải..."
                        emptyText="Không có KOC Livestream"
                        :sortable="false"
                        hasActions="true"
                    >
                        <x-slot name="actions">
                            <button class="btn-icon" title="Sửa" @click="handleEditKOC(row)" type="button">✏️</button>
                            <button class="btn-icon" title="Xóa" @click="handleDeleteKOC(row)" type="button">🗑️</button>
                        </x-slot>
                    </x-ui.tabular>
                    <x-ui.pagination id="campaign-kocs-pagination-livestream" page="currentPage" onPageSizeChange="pageSizeChange" />
                </x-ui.cards>
            </div>
        </div>

        {{-- Notes Chat Modal --}}
        <x-features.campaign.detail.notes-chat-modal />
    </div>

    {{-- Edit KOC Modal --}}
    <x-features.campaign.detail.edit-koc-modal />

    {{-- KOC Picker Modal --}}
    <x-features.campaign.detail.koc-picker-modal />

    {{-- Delete Confirmation Modal --}}
    <x-modals.confirm-modal
        id="confirmDeleteModal"
        title="Xác nhận xóa"
        message="Bạn có chắc muốn xóa KOC này khỏi chiến dịch?"
        level="warning"
        confirm-label="Xóa"
        onConfirm="confirmDeleteKOC"
    />

</div>
@endsection