@extends('layouts.app')

@section('content')
    <div id="creator-page"
         x-data="creatorPage()"
         x-init="init()"
         data-data-url="{{ route('creators.data') }}"
         data-metrics-url="{{ route('creators.metrics') }}"
         data-base-url="{{ url('/') }}"
         data-can-export="{{ $can_export ? '1' : '0' }}">

        <x-layout.page-header
            title="Quản Lý KOC"
            iconFa="bullhorn"
            iconFaStyle="fas"
            description="Quản lý tất cả các KOC cộng tác"
        />

        <div class="list-page-content">
            {{-- Stats Grid --}}
            <div class="list-page-stats-grid dashboard-grid" id="creator-stats">
                <div class="stat-card">
                    <div class="stat-label">Đang tải...</div>
                    <div class="stat-value">-</div>
                </div>
            </div>

            {{-- Filters & Toolbar --}}
            <x-ui.cards type="section-card" cardClass="list-page-card">
                <x-slot name="header">
                <div class="section-header-actions">
                    <x-ui.buttons type="button" id="add-koc-btn" variant="add" iconFa="plus" label="Thêm KOL/KOC" @click="openAddModal()" />

                    <div class="header-toolbar-actions">
                        <div class="header-search-wrap">
                            <div class="filter-search-inline">
                                <div class="search-input-icon">
                                    <x-fas-search class="search-icon" />
                                </div>
                                <input type="text" id="search-creators" placeholder="Tìm theo Tên KOL / Creator" class="search-input" x-model.debounce.300ms="filters.keyword" @keydown.enter="page = 1; loadRows()">
                            </div>
                        </div>
                        <x-ui.buttons type="button" variant="secondary" iconFa="filter" @click="filterExpanded = !filterExpanded" title="Bộ lọc mở rộng" />

                        <div class="btn-group">
                            <x-ui.buttons type="button" id="import-creators" variant="secondary" iconFa="file-import" label="Import" title="Import thêm KOC từ file Excel/CSV" @click="$refs.importFile.click()" />
                            <x-ui.buttons type="button" id="bulk-edit-creators" variant="secondary" iconFa="edit" label="Sửa loạt" title="Sửa hàng loạt KOC từ file Excel/CSV" @click="$refs.bulkEditFile.click()" />
                        </div>

                        <x-ui.buttons type="button" id="shuffle-creators" variant="secondary" iconFa="random" label="Xáo" title="Xáo trộn danh sách" @click="shuffleRows()" />

                        <div class="btn-group">
                            <x-ui.buttons type="button" id="download-template-creators" variant="secondary" iconFa="file-download" label="Mẫu" title="Tải mẫu Excel" @click="downloadTemplate()" />
                            <x-ui.buttons type="button" id="export-creators" variant="secondary" iconFa="file-export" label="Xuất" title="Xuất danh sách Excel" @click="exportCSV()" x-bind:disabled="!canExport" />
                        </div>
                        <x-ui.buttons type="button" id="sync-tiktok-btn" variant="secondary" iconFa="sync" label="Đồng bộ TikTok" title="Đồng bộ dữ liệu KOC từ TikTok Affiliate" @click="openSyncModal()" x-bind:disabled="syncing" />
                    </div>
                </div>
            </x-slot>

                <input type="file" x-ref="importFile" accept=".csv,.txt,.xlsx,.xls" style="display:none" @change="handleImportCSV($event)" />
                <input type="file" x-ref="bulkEditFile" accept=".csv,.txt,.xlsx,.xls" style="display:none" @change="handleBulkEditCSV($event)" />

                <div class="filter-quick-tags" id="filter-quick-tags"></div>

                {{-- Filter Panel --}}
                <div id="filter-panel" class="filter-panel" :class="{ 'is-collapsed': !filterExpanded }">
                    <div class="filter-row filter-row-single">
                        <div class="filter-item filter-item-pills">
                            <x-filters.filter-pills label="Kênh liên hệ" name="contact" class="filter-contact" :options="[
                                ['value' => 'phone', 'label' => 'SĐT'],
                                ['value' => 'zalo', 'label' => 'Zalo'],
                                ['value' => 'email', 'label' => 'Email'],
                            ]" />
                        </div>

                        <div class="filter-item filter-item-pills">
                            <x-filters.filter-pills label="Loại nội dung" name="advantage" class="filter-advantage" :options="[
                                ['value' => 'Video', 'label' => 'Video'],
                                ['value' => 'Livestream', 'label' => 'Live'],
                            ]" />
                        </div>

                        <div class="filter-item filter-item-range">
                            <div class="filter-item-label">Theo dõi</div>
                            <x-ui.filters type="range-filter" minId="creators-followers-min" maxId="creators-followers-max" />
                        </div>

                        <div class="filter-item filter-item-range">
                            <div class="filter-item-label">Doanh thu</div>
                            <x-ui.filters type="range-filter" minId="creators-gmv-min" maxId="creators-gmv-max" />
                        </div>

                        <div class="filter-item filter-item-range">
                            <div class="filter-item-label">Số món</div>
                            <x-ui.filters type="range-filter" minId="creators-items-min" maxId="creators-items-max" />
                        </div>

                        <div class="filter-item filter-item-select">
                            <div class="filter-item-label">Phân loại</div>
                            <select class="filter-select" x-model="filters.classification" @change="page = 1; loadRows()">
                                <option value="">Tất cả</option>
                                <option value="nano">Nano KOC</option>
                                <option value="micro">Micro KOC</option>
                                <option value="macro">Macro KOC</option>
                            </select>
                        </div>

                        <div class="filter-item filter-item-select">
                            <div class="filter-item-label">Content</div>
                            <select class="filter-select" x-model="filters.content" @change="page = 1; loadRows()">
                                <option value="">Tất cả</option>
                                <option value="affiliate">Affiliate</option>
                                <option value="unbox">Unbox</option>
                                <option value="review">Review</option>
                                <option value="live">Live</option>
                                <option value="oneshot">Oneshot</option>
                                <option value="thời trang">Thời trang</option>
                            </select>
                        </div>

                        <div class="filter-item filter-item-actions">
                            <div class="filter-actions-inline no-label">
                                <x-ui.buttons type="button" variant="ghost" iconFa="undo" title="Đặt lại" @click="resetFilters()" />
                                <button type="button" class="btn btn-primary" @click="collectFilters(); page = 1; loadRows()">Áp dụng</button>
                            </div>
                        </div>
                    </div>
                </div>
            </x-ui.cards>

            {{-- Data Table --}}
            @php
                $toggleableColumns = [
                    ['key' => 'links', 'label' => 'Link'],
                    ['key' => 'contact', 'label' => 'Liên hệ'],
                    ['key' => 'content', 'label' => 'Content'],
                    ['key' => 'followers', 'label' => 'Followers'],
                    ['key' => 'gmv', 'label' => 'GMV'],
                    ['key' => 'items', 'label' => 'Số món bán ra'],
                    ['key' => 'average_views', 'label' => 'View TB'],
                    ['key' => 'advantages', 'label' => 'Lợi thế'],
                    ['key' => 'classification', 'label' => 'Phân loại'],
                    ['key' => 'audience', 'label' => 'Tệp khách'],
                    ['key' => 'notes', 'label' => 'Ghi chú'],
                    ['key' => 'campaigns_count', 'label' => 'Số chiến dịch'],
                ];

                $creatorColumns = [
                        ['key' => 'creator_name', 'label' => 'Tên KOL / Creator', 'toggleable' => false, 'cellClass' => 'col-left', 'widthClass' => 'col-lg', 'sticky' => 'left'],
                        ['key' => 'links', 'label' => 'Link', 'render' => 'window.buildSocialLinksHtml(row)', 'cellClass' => 'col-left', 'widthClass' => 'col-link', 'truncate' => false],
                        ['key' => 'contact', 'label' => 'Liên hệ', 'render' => 'window.buildContactButtonHtml(row)', 'cellClass' => 'col-center', 'widthClass' => 'col-sm', 'truncate' => false],
                        ['key' => 'content', 'label' => 'Content', 'cellClass' => 'col-left', 'widthClass' => 'col-md'],
                        ['key' => 'followers', 'label' => 'Followers', 'type' => 'number', 'sortable' => true, 'cellClass' => 'col-right number-cell', 'widthClass' => 'col-md', 'truncate' => false],
                        ['key' => 'gmv', 'label' => 'GMV', 'type' => 'number', 'sortable' => true, 'cellClass' => 'col-right number-cell', 'widthClass' => 'col-md', 'truncate' => false],
                        ['key' => 'items', 'label' => 'Số món bán ra', 'type' => 'number', 'sortable' => true, 'cellClass' => 'col-right number-cell', 'widthClass' => 'col-md', 'truncate' => false],
                        ['key' => 'average_views', 'label' => 'View TB', 'type' => 'number', 'sortable' => true, 'cellClass' => 'col-right number-cell', 'widthClass' => 'col-md', 'truncate' => false],
                        ['key' => 'advantages', 'label' => 'Lợi thế', 'cellClass' => 'col-left', 'widthClass' => 'col-md'],
                        ['key' => 'classification', 'label' => 'Phân loại', 'render' => 'window.buildClassificationBadgeHtml(row.classification)', 'cellClass' => 'col-center', 'widthClass' => 'col-sm', 'truncate' => false],
                        ['key' => 'audience', 'label' => 'Tệp khách', 'cellClass' => 'col-left', 'widthClass' => 'col-md'],
                        ['key' => 'campaigns_count', 'label' => 'Số chiến dịch', 'type' => 'number', 'sortable' => true, 'cellClass' => 'col-right number-cell', 'widthClass' => 'col-md', 'truncate' => false],
                        ['key' => 'notes', 'label' => 'Ghi chú', 'cellClass' => 'col-left', 'widthClass' => 'col-sm'],
                    ];
                @endphp

            <div x-data="columnVisibility({
                columns: {{ Illuminate\Support\Js::from($toggleableColumns) }},
            })">
            <x-ui.cards type="section-card" title='Danh sách KOC <span x-show="lastSyncAt" class="text-sm font-normal text-gray-500 ml-3"><svg class="w-3.5 h-3.5 inline-block align-middle" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M440.65 12.57l4 82.77A247.16 247.16 0 0 0 255.83 8C134.73 8 33.91 94.92 12.29 209.82A12 12 0 0 0 24.09 224h49.05a12 12 0 0 0 11.67-9.26 175.91 175.91 0 0 1 317-56.94l-101.46-4.86a12 12 0 0 0-12.57 12v47.41a12 12 0 0 0 12 12H500a12 12 0 0 0 12-12V12a12 12 0 0 0-12-12h-47.37a12 12 0 0 0-11.98 12.57zM255.83 432a175.61 175.61 0 0 1-146-77.8l101.8 4.87a12 12 0 0 0 12.57-12v-47.4a12 12 0 0 0-12-12H12a12 12 0 0 0-12 12V500a12 12 0 0 0 12 12h47.35a12 12 0 0 0 12-12.6l-4.15-82.57A247.17 247.17 0 0 0 255.83 504c121.11 0 221.93-86.92 243.55-201.82a12 12 0 0 0-11.8-14.18h-49.05a12 12 0 0 0-11.67 9.26A175.86 175.86 0 0 1 255.83 432z"/></svg> <span class="align-middle" x-text="lastSyncAt"></span> <span class="align-middle">[KOC <span x-text="lastSyncFrom"></span>-<span x-text="lastSyncTo"></span>]</span></span>' cardClass="list-page-card list-page-table-card">
                <x-slot name="header">
                    <div class="bulk-actions-inline" x-show="selected.length > 0" x-cloak>
                        <span class="bulk-selection-label">Đã chọn</span>
                        <strong class="bulk-selection-count" x-text="selected.length"></strong>
                        <button class="btn btn-primary btn-sm bulk-action-btn" @click="openBulkAddModal()">Thêm vào chiến dịch</button>
                        <button class="btn btn-secondary btn-sm bulk-action-btn" @click="exportSelectedCSV()" x-bind:disabled="!canExport" x-bind:title="!canExport ? '🚫 Không thể thực hiện' : 'Xuất các KOC đã chọn'">Xuất đã chọn</button>
                        <button class="btn btn-danger btn-sm bulk-action-btn" @click="bulkDeleteSelected()">Xoá KOC đã chọn</button>
                    </div>
                    <x-ui.column-visibility />
                </x-slot>

                <x-ui.tabular
                    id="creators-table"
                    :columns="$creatorColumns"
                    column-visibility="visible"
                    rows="rows"
                    loading="loading"
                    loadingText="Đang tải dữ liệu..."
                    emptyText="Chưa có KOC nào"
                    bulkActions="selected"
                    selectAll="selectAll"
                    :sortable="true"
                    hasActions="true"
                >
                    <x-slot name="actions">
                        <button class="btn-icon" @click="openEditModal(row)" title="Sửa">&#x270F;&#xFE0F;</button>
                        <button class="btn-icon btn-icon-danger" @click="confirmDelete(row.id)" title="Xóa">&#x1F5D1;&#xFE0F;</button>
                    </x-slot>
                </x-ui.tabular>

                {{-- Pagination --}}
                <div class="list-page-pagination" id="creators-pagination">
                    <div class="pagination-left">
                        <label class="pagination-size">
                            <span>Hiển thị:</span>
                            <select x-model.number="pageSize" @change="pageSizeChange()">
                                <option value="10">10</option>
                                <option value="20">20</option>
                                <option value="50">50</option>
                                <option value="100">100</option>
                            </select>
                        </label>
                        <span class="pagination-info" x-text="startItem + '–' + endItem"></span>
                    </div>
                    <div class="pagination-center">
                        <button class="pagination-btn pagination-prev" type="button" @click="prevPage()" :disabled="page <= 1">‹</button>
                        <div class="pagination-pages">
                            <template x-if="page > 4">
                                <a href="javascript:void(0)" class="pagination-page-btn" @click="goToPage(1)">1</a>
                            </template>
                            <template x-if="page > 5">
                                <span class="pagination-ellipsis">…</span>
                            </template>
                            <template x-for="p in visiblePages" :key="p">
                                <a href="javascript:void(0)" class="pagination-page-btn" :class="{ 'active': p === page }" @click="goToPage(p)" x-text="p"></a>
                            </template>
                            <template x-if="page < totalPages - 4">
                                <span class="pagination-ellipsis">…</span>
                            </template>
                            <template x-if="page < totalPages - 3">
                                <a href="javascript:void(0)" class="pagination-page-btn" @click="goToPage(totalPages)" x-text="totalPages"></a>
                            </template>
                        </div>
                        <button class="pagination-btn pagination-next" type="button" @click="nextPage()" :disabled="page >= totalPages">›</button>
                    </div>
                </div>
            </x-ui.cards>
        </div>
        </div>

        {{-- Add Modal --}}
        <x-features.creator.creator-modal
            id="addCreatorModal"
            title="Thêm KOL / KOC"
            formId="addCreatorForm"
            submitLabel="Thêm KOL/KOC"
            mode="create"
        />

        {{-- Edit Modal --}}
        <x-features.creator.creator-modal
            id="editCreatorModal"
            title="Sửa KOL / KOC"
            formId="editCreatorForm"
            submitLabel="Lưu thay đổi"
            mode="edit"
        />

        <x-features.creator.tiktok-sync-modals />

        {{-- Campaign Select Modal --}}
        <x-ui.modals type="modal" id="campaignSelectModal" title="Chọn chiến dịch" size="sm">
            <div class="form-row">
                <x-form.label for="campaignSelect" required>Chiến dịch</x-form.label>
                <select id="campaignSelect" class="form-select" required x-model="bulkCampaignId" style="width:100%;">
                    <option value="">-- Chọn chiến dịch --</option>
                    <template x-for="c in bulkCampaigns" :key="c.id">
                        <option :value="c.id" x-text="c.campaign_name || c.name || 'Không tên'"></option>
                    </template>
                </select>
            </div>
            <div class="form-row" style="margin-top:12px;">
                <x-form.label required>Loại booking</x-form.label>
                <div class="flex items-center gap-4" style="display:flex;gap:16px;padding-top:4px;">
                    <label class="checkbox-item" style="display:flex;align-items:center;gap:6px;cursor:pointer;">
                        <input type="radio" name="bulkBookingType" value="video" x-model="bulkBookingType" />
                        <span>Video</span>
                    </label>
                    <label class="checkbox-item" style="display:flex;align-items:center;gap:6px;cursor:pointer;">
                        <input type="radio" name="bulkBookingType" value="livestream" x-model="bulkBookingType" />
                        <span>Livestream</span>
                    </label>
                </div>
            </div>
            <x-slot name="footer">
                <x-ui.buttons type="button" variant="ghost" label="Hủy" @click="modalClose('campaignSelectModal')" />
                <x-ui.buttons type="button" variant="primary" label="Xác nhận" @click="handleBulkAddToCampaign()" />
            </x-slot>
        </x-ui.modals>

        {{-- Delete Confirmation Modal --}}
        <x-modals.confirm-modal
            id="deleteCreatorConfirmModal"
            title="Xác nhận xóa"
            message="Bạn có chắc chắn muốn xóa KOL/KOC này? Hành động này không thể hoàn tác."
            level="error"
            confirm-label="Xóa"
            onConfirm="executeDeleteCreator"
        />

        {{-- Bulk Delete Confirmation Modal --}}
        <x-modals.confirm-modal
            id="bulkDeleteCreatorConfirmModal"
            title="Xác nhận xóa hàng loạt"
            level="error"
            confirm-label="Xóa"
            onConfirm="executeBulkDeleteSelected"
        >
            <p class="text-gray-600" x-text="'Bạn có chắc chắn muốn xóa ' + selected.length + ' KOC đã chọn? Hành động này không thể hoàn tác.'"></p>
        </x-modals.confirm-modal>
    </div>

@endsection
