@extends('layouts.app')

@section('content')
    <div id="analysis-page" x-data="analysisPage()">
        <x-layout.page-header
            title="Đơn hàng liên kết"
            iconFa="chart-pie"
            description="Upload file Excel / CSV để phân tích đơn hàng liên kết nhanh chóng."
        >
            <form id="analysis-upload-form" @@submit.prevent="handleUpload" class="analysis-header-form">
                @csrf
                {{-- Trạng thái chờ --}}
                <div class="analysis-dropzone-trigger"
                     x-show="!uploading && !fileSelected"
                     :class="{ 'drag-over': dragOver }"
                     @@dragover.prevent="dragOver = true"
                     @@dragleave.prevent="dragOver = false"
                     @@drop.prevent="handleDrop($event); dragOver = false">
                    <span class="analysis-trigger-icon">@svg('fas-cloud-upload-alt')</span>
                    <span class="analysis-trigger-text">Kéo thả hoặc chọn file</span>
                    <span class="analysis-trigger-hint">.xlsx .xls .csv — 20MB</span>
                    <label class="btn analysis-btn-upload">
                        @svg('fas-folder-open')
                        <span>Chọn file</span>
                        <input type="file" name="file" accept=".xlsx,.xls,.csv" @@change="handleFileSelect" hidden>
                    </label>
                </div>

                {{-- Trạng thái đã chọn file --}}
                <div class="analysis-file-info" x-show="fileSelected && !uploading" x-cloak>
                    <span class="analysis-file-badge">
                        @svg('fas-file-excel')
                        <span x-text="fileName"></span>
                        <span class="analysis-file-size" x-text="fileSize"></span>
                    </span>
                    <button type="submit" class="btn" :disabled="uploading">
                        @svg('fas-chart-bar')
                        <span>Phân tích</span>
                    </button>
                    <button type="button" class="btn" @@click="resetUpload" :disabled="uploading" title="Bỏ chọn">
                        @svg('fas-times')
                    </button>
                </div>

                {{-- Trạng thái đang xử lý --}}
                <div class="analysis-loading" x-show="uploading" x-cloak>
                    <span class="analysis-spin"></span>
                    <span>Đang xử lý...</span>
                </div>

                {{-- Nút xoá dữ liệu — bên phải cùng --}}
                <button type="button" class="btn btn-sm btn-ghost analysis-header-clear" @@click="clearData" x-show="result" x-cloak>
                    @svg('fas-trash-alt')
                    <span>Xoá dữ liệu</span>
                </button>
            </form>
        </x-layout.page-header>

        <div class="list-page-content">
            <p class="error-text" x-show="errorMessage" x-text="errorMessage" x-cloak></p>

            {{-- Affiliate metrics — luôn hiển thị cấu trúc card, có dữ liệu thì điền vào --}}
            <div class="list-page-stats-grid">
                <x-ui.cards type="card-grid-2x2" class="stat-kpi-card">
                    <x-slot name="item1"><div class="stat-label">Tổng đơn</div></x-slot>
                    <x-slot name="item2"><div class="stat-icon">🛒</div></x-slot>
                    <x-slot name="item3"><div class="stat-value" x-text="formatNum(result?.affiliate_metrics?.total_orders)">0</div></x-slot>
                    <x-slot name="item4"><div class="stat-sub" x-html="fmtBreakdown(result?.affiliate_metrics?.organic_orders, result?.affiliate_metrics?.ad_orders)"></div></x-slot>
                </x-ui.cards>
                <x-ui.cards type="card-grid-2x2" class="stat-kpi-card">
                    <x-slot name="item1"><div class="stat-label">Creator</div></x-slot>
                    <x-slot name="item2"><div class="stat-icon">👤</div></x-slot>
                    <x-slot name="item3"><div class="stat-value" x-text="formatNum(result?.affiliate_metrics?.unique_creators)">0</div></x-slot>
                    <x-slot name="item4"></x-slot>
                </x-ui.cards>
                <x-ui.cards type="card-grid-2x2" class="stat-kpi-card">
                    <x-slot name="item1"><div class="stat-label">Sản phẩm</div></x-slot>
                    <x-slot name="item2"><div class="stat-icon">📦</div></x-slot>
                    <x-slot name="item3"><div class="stat-value" x-text="formatNum(result?.affiliate_metrics?.unique_products)">0</div></x-slot>
                    <x-slot name="item4"><div class="stat-sub" x-text="'Số lượng: ' + formatNum(result?.affiliate_metrics?.total_quantity)"></div></x-slot>
                </x-ui.cards>
                <x-ui.cards type="card-grid-2x2" class="stat-kpi-card">
                    <x-slot name="item1"><div class="stat-label">HH Ước tính / D.Thu</div></x-slot>
                    <x-slot name="item2"><div class="stat-icon">⚖️</div></x-slot>
                    <x-slot name="item3"><div class="stat-value" x-text="formatNum(result?.affiliate_metrics?.commission_ratio_est) + '%'">0%</div></x-slot>
                    <x-slot name="item4"><div class="stat-sub" x-html="fmtStdAdRatio(result?.affiliate_metrics?.std_commission_ratio_est, result?.affiliate_metrics?.ad_commission_ratio_est)"></div></x-slot>
                </x-ui.cards>
                <x-ui.cards type="card-grid-2x2" class="stat-kpi-card stat-kpi-card--revenue">
                    <x-slot name="item1"><div class="stat-label">Tổng doanh thu (VND)</div></x-slot>
                    <x-slot name="item2"><div class="stat-icon">💵</div></x-slot>
                    <x-slot name="item3"><div class="stat-value" x-text="formatNum(result?.affiliate_metrics?.total_revenue)">0</div></x-slot>
                    <x-slot name="item4"><div class="stat-sub" x-html="fmtBreakdown(result?.affiliate_metrics?.std_revenue, result?.affiliate_metrics?.ad_revenue)"></div></x-slot>
                </x-ui.cards>
                <x-ui.cards type="card-grid-2x2" class="stat-kpi-card">
                    <x-slot name="item1"><div class="stat-label">Hoa hồng thực tế (VND)</div></x-slot>
                    <x-slot name="item2"><div class="stat-icon">💰</div></x-slot>
                    <x-slot name="item3"><div class="stat-value" x-text="formatNum(result?.affiliate_metrics?.total_actual_commission)">0</div></x-slot>
                    <x-slot name="item4"><div class="stat-sub" x-html="fmtBreakdown(result?.affiliate_metrics?.std_actual_commission, result?.affiliate_metrics?.ad_actual_commission)"></div></x-slot>
                </x-ui.cards>
                <x-ui.cards type="card-grid-2x2" class="stat-kpi-card">
                    <x-slot name="item1"><div class="stat-label">Hoa hồng ước tính (VND)</div></x-slot>
                    <x-slot name="item2"><div class="stat-icon">📈</div></x-slot>
                    <x-slot name="item3"><div class="stat-value" x-text="formatNum(result?.affiliate_metrics?.total_estimated_commission)">0</div></x-slot>
                    <x-slot name="item4"><div class="stat-sub" x-html="fmtBreakdown(result?.affiliate_metrics?.std_estimated_commission, result?.affiliate_metrics?.ad_estimated_commission)"></div></x-slot>
                </x-ui.cards>
            </div>

            {{-- 3 biểu đồ: nội dung, trạng thái, theo ngày — cùng hàng --}}
            <div class="analysis-charts-row">
                <x-ui.cards type="section-card" cardClass="list-page-card">
                    <x-slot name="header">
                        <div class="section-header-actions db-header-full">
                            <div class="db-panel-header-row">
                                <span class="db-panel-dot db-panel-dot--purple"></span>
                                <span class="db-panel-title">Nội dung</span>
                            </div>
                        </div>
                    </x-slot>
                    <div class="db-panel-inner">
                        <div class="db-cost-inner-row">
                            <div class="db-cost-chart-area">
                                <svg id="analysis-ct-chart-svg" x-ref="ctSvg" class="db-chart-svg"></svg>
                                <div id="analysis-ct-chart-tooltip" x-ref="ctTooltip" class="db-chart-tooltip" style="display:none"></div>
                            </div>
                            <div id="analysis-ct-chart-legend" x-ref="ctLegend" class="db-cost-types-panel"></div>
                        </div>
                    </div>
                </x-ui.cards>
                <x-ui.cards type="section-card" cardClass="list-page-card">
                    <x-slot name="header">
                        <div class="section-header-actions db-header-full">
                            <div class="db-panel-header-row">
                                <span class="db-panel-dot db-panel-dot--amber"></span>
                                <span class="db-panel-title">Trạng thái đơn hàng</span>
                            </div>
                        </div>
                    </x-slot>
                    <div class="db-panel-inner">
                        <div class="db-cost-inner-row">
                            <div class="db-cost-chart-area">
                                <svg id="analysis-st-chart-svg" x-ref="stSvg" class="db-chart-svg"></svg>
                                <div id="analysis-st-chart-tooltip" x-ref="stTooltip" class="db-chart-tooltip" style="display:none"></div>
                            </div>
                            <div id="analysis-st-chart-legend" x-ref="stLegend" class="db-cost-types-panel"></div>
                        </div>
                    </div>
                </x-ui.cards>
                <x-ui.cards type="section-card" cardClass="list-page-card">
                    <x-slot name="header">
                        <div class="section-header-actions db-header-full">
                            <div class="db-panel-header-row">
                                <span class="db-panel-dot db-panel-dot--blue"></span>
                                <span class="db-panel-title">Đơn hàng/Doanh thu theo ngày</span>
                            </div>
                        </div>
                    </x-slot>
                    <div class="db-panel-inner">
                        <div class="analysis-daily-body">
                            <div class="analysis-daily-chart-area">
                                <svg id="analysis-daily-chart-svg" x-ref="dailySvg" class="analysis-daily-svg"></svg>
                                <div id="analysis-daily-chart-tooltip" x-ref="dailyTooltip" class="db-chart-tooltip" style="display:none"></div>
                            </div>
                            <div id="analysis-daily-chart-legend" x-ref="dailyLegend" class="analysis-daily-legend"></div>
                        </div>
                    </div>
                </x-ui.cards>
            </div>

            {{-- 2 bảng song song — mỗi bên 1 nửa --}}
            <div class="analysis-tables-row">
                {{-- Bảng top creator --}}
                <div class="section-card analysis-section-card-top analysis-card-half">
                    <div class="section-card-header">
                        <div class="db-panel-header-row-full">
                            <span class="db-panel-dot db-panel-dot--emerald"></span>
                            <span class="db-panel-title">Top creator theo doanh thu</span>
                            <span class="analysis-legend">TC: Tiêu chuẩn · QC: Quảng cáo · HH: Hoa hồng · DT: Doanh thu</span>
                        </div>
                    </div>
                    <div class="section-card-body analysis-top-table-body">
                        <div class="table-scroll">
                        <table class="tabular-table analysis-top-table">
                        <thead>
                            <tr class="border-b border-gray-200 analysis-thead-group">
                                <th rowspan="2" class="col-center col-xxs">STT</th>
                                <th rowspan="2" class="col-left col-sm">Creator</th>
                                <th rowspan="2" class="col-right col-xms">Đơn</th>
                                <th rowspan="2" class="col-right col-sm">Doanh thu</th>
                                <th class="analysis-group-est" colspan="4">Ước tính</th>
                                <th class="analysis-group-act" colspan="4">Thực tế</th>
                            </tr>
                            <tr class="analysis-thead-sub">
                                <th class="col-right col-xs analysis-sub-est analysis-sub-border">HH T.chuẩn</th>
                                <th class="col-right col-xs analysis-sub-est">HH Q.cáo</th>
                                <th class="col-right col-xs analysis-sub-est">Tổng HH</th>
                                <th class="col-right col-xms analysis-sub-est">HH/DT</th>
                                <th class="col-right col-xs analysis-sub-act analysis-sub-border">HH T.chuẩn</th>
                                <th class="col-right col-xs analysis-sub-act">HH Q.cáo</th>
                                <th class="col-right col-xs analysis-sub-act">Tổng HH</th>
                                <th class="col-right col-xms analysis-sub-act">HH/DT</th>
                            </tr>
                        </thead>
                            <tbody>
                                <template x-if="topCreators.length > 0">
                                    <template x-for="row in topCreators" :key="row.name">
                                        <tr class="border-b border-gray-100 hover:bg-gray-50">
                                            <td class="col-center col-xxs" x-text="row.stt"></td>
                                            <td class="col-left col-sm cell-truncate" x-text="row.name" :title="row.name"></td>
                                            <td class="col-right col-xms" x-text="formatNumber(row.orders)"></td>
                                            <td class="col-right col-sm" x-text="formatNumber(row.revenue)"></td>
                                            <td class="col-right col-xs" x-text="formatNumber(row.std_commission_est)"></td>
                                            <td class="col-right col-xs" x-text="formatNumber(row.ad_commission_est)"></td>
                                            <td class="col-right col-xs" x-text="formatNumber(row.total_commission_est)"></td>
                                            <td class="col-right col-xms" x-text="formatNumber(row.commission_ratio_act) + '%'"></td>
                                            <td class="col-right col-xs" x-text="formatNumber(row.std_commission_act)"></td>
                                            <td class="col-right col-xs" x-text="formatNumber(row.ad_commission_act)"></td>
                                            <td class="col-right col-xs" x-text="formatNumber(row.total_commission_act)"></td>
                                            <td class="col-right col-xms" x-text="formatNumber(row.commission_ratio_est) + '%'"></td>
                                        </tr>
                                    </template>
                                </template>
                                <template x-if="topCreators.length === 0">
                                    <tr>
                                        <td colspan="12" class="col-center" style="padding: 24px 10px; color: var(--gray-500);">Chưa có dữ liệu — hãy tải lên file phân tích</td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                        </div>
                    </div>
                </div>

                {{-- Bảng top sản phẩm --}}
                <div class="section-card analysis-section-card-top analysis-card-half">
                    <div class="section-card-header">
                        <div class="db-panel-header-row-full">
                            <span class="db-panel-dot db-panel-dot--Cyan"></span>
                            <span class="db-panel-title">Top sản phẩm theo doanh thu</span>
                            <span class="analysis-legend">TC: Tiêu chuẩn · QC: Quảng cáo · HH: Hoa hồng · DT: Doanh thu</span>
                        </div>
                    </div>
                    <div class="section-card-body analysis-top-table-body">
                        <div class="table-scroll">
                        <table class="tabular-table analysis-top-table">
                        <thead>
                            <tr class="border-b border-gray-200 analysis-thead-group">
                                <th rowspan="2" class="col-center col-xxs">STT</th>
                                <th rowspan="2" class="col-left col-sm">Sản phẩm</th>
                                <th rowspan="2" class="col-right col-xms">Đơn</th>
                                <th rowspan="2" class="col-right col-sm">Doanh thu</th>
                                <th class="analysis-group-est" colspan="4">Ước tính</th>
                                <th class="analysis-group-act" colspan="4">Thực tế</th>
                            </tr>
                            <tr class="analysis-thead-sub">
                                <th class="col-right col-xs analysis-sub-est analysis-sub-border">HH T.chuẩn</th>
                                <th class="col-right col-xs analysis-sub-est">HH Q.cáo</th>
                                <th class="col-right col-xs analysis-sub-est">Tổng HH</th>
                                <th class="col-right col-xms analysis-sub-est">HH/DT</th>
                                <th class="col-right col-xs analysis-sub-act analysis-sub-border">HH T.chuẩn</th>
                                <th class="col-right col-xs analysis-sub-act">HH Q.cáo</th>
                                <th class="col-right col-xs analysis-sub-act">Tổng HH</th>
                                <th class="col-right col-xms analysis-sub-act">HH/DT</th>
                            </tr>
                        </thead>
                            <tbody>
                                <template x-if="topProducts.length > 0">
                                    <template x-for="row in topProducts" :key="row.product_id">
                                        <tr class="border-b border-gray-100 hover:bg-gray-50" :class="{'analysis-row-selected': selectedProductId === row.product_id}" style="cursor:pointer" @@click="selectProduct(row.product_id, row.name)">
                                            <td class="col-center col-xxs" x-text="row.stt"></td>
                                            <td class="col-left col-sm cell-truncate" x-text="row.name" :title="row.name"></td>
                                            <td class="col-right col-xms" x-text="formatNumber(row.orders)"></td>
                                            <td class="col-right col-sm" x-text="formatNumber(row.revenue)"></td>
                                            <td class="col-right col-xs" x-text="formatNumber(row.std_commission_est)"></td>
                                            <td class="col-right col-xs" x-text="formatNumber(row.ad_commission_est)"></td>
                                            <td class="col-right col-xs" x-text="formatNumber(row.total_commission_est)"></td>
                                            <td class="col-right col-xms" x-text="formatNumber(row.commission_ratio_act) + '%'"></td>
                                            <td class="col-right col-xs" x-text="formatNumber(row.std_commission_act)"></td>
                                            <td class="col-right col-xs" x-text="formatNumber(row.ad_commission_act)"></td>
                                            <td class="col-right col-xs" x-text="formatNumber(row.total_commission_act)"></td>
                                            <td class="col-right col-xms" x-text="formatNumber(row.commission_ratio_est) + '%'"></td>
                                        </tr>
                                    </template>
                                </template>
                                <template x-if="topProducts.length === 0">
                                    <tr>
                                        <td colspan="12" class="col-center" style="padding: 24px 10px; color: var(--gray-500);">Chưa có dữ liệu — hãy tải lên file phân tích</td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                        </div>
                    </div>
                </div>
            </div>

            {{-- Bảng chi tiết dữ liệu đơn hàng — toàn màn hình, dùng x-ui.tabular --}}
            @php
                $orderDetailColumns = [
                    ['key' => 'order_id', 'label' => 'ID đơn hàng', 'cellClass' => 'col-left', 'widthClass' => 'col-mid', 'truncate' => true],
                    ['key' => 'created_at_display', 'label' => 'Thời gian tạo', 'cellClass' => 'col-left', 'widthClass' => 'col-mid', 'truncate' => true],
                    ['key' => 'creator', 'label' => 'Creator', 'cellClass' => 'col-left', 'widthClass' => 'col-mid', 'truncate' => true],
                    ['key' => 'content_type', 'label' => 'Loại nội dung', 'cellClass' => 'col-left', 'widthClass' => 'col-xs', 'truncate' => true],
                    ['key' => 'product_name', 'label' => 'Tên sản phẩm', 'cellClass' => 'col-left', 'widthClass' => 'col-md', 'truncate' => true],
                    ['key' => 'quantity', 'label' => 'SL', 'type' => 'number', 'cellClass' => 'col-right', 'widthClass' => 'col-xxs', 'truncate' => false],
                    ['key' => 'status', 'label' => 'Trạng thái ĐH', 'cellClass' => 'col-left', 'widthClass' => 'col-mid', 'truncate' => true],
                    ['key' => 'commission_base_est', 'label' => 'Cơ sở HH', 'type' => 'number', 'cellClass' => 'col-right', 'widthClass' => 'col-xs', 'truncate' => false],
                    ['key' => 'std_commission_est', 'label' => 'HH T.chuẩn ƯT', 'type' => 'number', 'cellClass' => 'col-right', 'widthClass' => 'col-xs', 'truncate' => false],
                    ['key' => 'std_commission_act', 'label' => 'HH T.chuẩn TT', 'type' => 'number', 'cellClass' => 'col-right', 'widthClass' => 'col-xs', 'truncate' => false],
                    ['key' => 'ad_commission_est', 'label' => 'HH Q.cáo ƯT', 'type' => 'number', 'cellClass' => 'col-right', 'widthClass' => 'col-xs', 'truncate' => false],
                    ['key' => 'ad_commission_act', 'label' => 'HH Q.cáo TT', 'type' => 'number', 'cellClass' => 'col-right', 'widthClass' => 'col-xs', 'truncate' => false],
                    ['key' => 'total_commission_est', 'label' => 'Tổng HH ƯT', 'type' => 'number', 'cellClass' => 'col-right', 'widthClass' => 'col-xs', 'truncate' => false],
                    ['key' => 'total_commission_act', 'label' => 'Tổng HH TT', 'type' => 'number', 'cellClass' => 'col-right', 'widthClass' => 'col-xs', 'truncate' => false],
                ];
            @endphp
            <div class="analysis-order-detail-section">
                <x-ui.cards type="section-card" title="Chi tiết dữ liệu đơn hàng" cardClass="list-page-card">
                    <x-slot name="header">
                        <div class="section-header-actions">
                            <span class="analysis-order-count" x-show="orderDetails.length > 0" x-cloak>
                                <span x-text="filteredOrderDetails.length"></span>/<span x-text="orderDetails.length"></span> đơn
                            </span>
                            <div class="filter-search-inline">
                                <div class="search-input-icon search-input-icon--action" @@click="applySearchCreator()">
                                    @svg('fas-search', 'search-icon')
                                </div>
                                <input type="text" placeholder="Tìm Creator" class="search-input" x-model="orderSearchCreatorInput" @@keydown="applySearchCreatorOnEnter($event)">
                            </div>
                            <div class="filter-search-inline">
                                <div class="search-input-icon search-input-icon--action" @@click="applySearchProduct()">
                                    @svg('fas-search', 'search-icon')
                                </div>
                                <input type="text" placeholder="Tìm Sản phẩm" class="search-input" x-model="orderSearchProductInput" @@keydown="applySearchProductOnEnter($event)">
                            </div>
                            <div class="filter-date-range">
                                <input type="date" class="filter-date-input" x-model="orderDateFrom" placeholder="Từ ngày">
                                <span class="filter-date-sep">→</span>
                                <input type="date" class="filter-date-input" x-model="orderDateTo" placeholder="Đến ngày">
                            </div>
                            <select class="filter-select" x-model="orderFilterContentType">
                                <option value="">Loại nội dung</option>
                                <template x-for="opt in orderContentTypeOptions" :key="opt">
                                    <option :value="opt" x-text="opt"></option>
                                </template>
                            </select>
                            <select class="filter-select" x-model="orderFilterStatus">
                                <option value="">Trạng thái đơn hàng</option>
                                <template x-for="opt in orderStatusOptions" :key="opt">
                                    <option :value="opt" x-text="opt"></option>
                                </template>
                            </select>
                            <x-ui.buttons type="button" variant="ghost" iconFa="undo" title="Đặt lại" @click="resetOrderFilters()" />
                        </div>
                    </x-slot>
                    <x-ui.tabular
                        id="order-detail-table"
                        :columns="$orderDetailColumns"
                        rows="filteredOrderDetails"
                        :sortable="false"
                        loadingText=""
                        emptyText="Chưa có dữ liệu — hãy tải lên file phân tích"
                        rowKey="order_id"
                    />
                </x-ui.cards>
            </div>
        </div>
    </div>
@endsection
