{% extends 'ewoooc_base.html' %}

{% block title %}EwoooC 活動看板{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/page-edm-v2.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/page-edm.css') }}">
{% endblock %}

{% block ewooo_content %}
{% set current_endpoint = 'edm.' ~ current_promo_page ~ '_dashboard' %}
{% set current_stats = {'new': 0, 'up': 0, 'down': 0, 'delisted_last_run': 0, 'on_shelf': 0} %}
{% if active_tab in slot_stats %}
    {% set current_stats = slot_stats[active_tab] %}
{% elif slot_stats %}
    {% set current_stats = slot_stats.values() | list | first %}
{% endif %}
{% set task_key = 'festival_task' if current_promo_page == 'festival' else 'edm_task' %}
{% set run_list = scheduler_stats.get(task_key, []) %}
{% set latest_run = run_list[0] if run_list else None %}

<div class="campaign-stack edm-page" data-promo="{{ current_promo_page }}">
    <section>
        <div class="campaign-switcher">
            {% for page in promo_pages %}
                <a class="campaign-tab {% if page.id == current_promo_page %}is-active{% endif %}" href="{{ page.url }}">
                    <span>{{ page.name }}</span>
                    {% if page.id == current_promo_page %}
                        <span class="campaign-tab-count momo-mono">{{ total_edm_products | number_format }}</span>
                    {% endif %}
                </a>
            {% endfor %}
        </div>
    </section>

    <section class="campaign-hero-grid">
        <div class="campaign-hero is-{{ current_promo_page|replace('_', '-') }}">
            <div class="campaign-hero-content">
                <div class="campaign-eyebrow">
                    <span class="campaign-eyebrow-label">CAMPAIGN</span>
                    <span class="campaign-promo-id momo-mono">ID · {{ current_promo_page|upper }}</span>
                </div>
                <h1 class="campaign-title">{{ page_title }}</h1>
                <p class="campaign-growth-copy">用活動價格異動找主推、補貨與曝光機會。</p>
                <div class="campaign-meta-grid momo-mono">
                    <div>
                        <div class="campaign-meta-label">活動時段</div>
                        <div class="campaign-meta-value">{{ activity_time }}</div>
                    </div>
                    <div>
                        <div class="campaign-meta-label">最後更新</div>
                        <div class="campaign-meta-value">{{ last_update }}</div>
                    </div>
                    <div>
                        <div class="campaign-meta-label">商品總數</div>
                        <div class="campaign-meta-value campaign-meta-value--total">{{ total_edm_products | number_format }}</div>
                    </div>
                </div>

                <div class="campaign-actions">
                    {% if current_promo_page == 'edm' %}
                        <button class="campaign-action" type="button" data-campaign-task="edm">
                            <i class="fas fa-rotate"></i> 手動更新
                        </button>
                        <button class="campaign-action is-light" type="button" data-campaign-task="notification">
                            <i class="fas fa-bell"></i> 發送通知
                        </button>
                    {% elif current_promo_page == 'festival' %}
                        <button class="campaign-action" type="button" data-campaign-task="festival">
                            <i class="fas fa-rotate"></i> 手動更新
                        </button>
                    {% endif %}
                </div>
            </div>
        </div>

        <aside class="campaign-kpi-panel">
            <div class="campaign-panel-title">
                <i class="fas fa-chart-line"></i>
                <span>活動數據</span>
            </div>
            <div class="campaign-kpi-grid">
                <div class="campaign-kpi">
                    <div class="campaign-kpi-label">上架商品</div>
                    <div class="campaign-kpi-value momo-mono">{{ current_stats.get('on_shelf', 0) | number_format }}</div>
                </div>
                <div class="campaign-kpi">
                    <div class="campaign-kpi-label">新品</div>
                    <div class="campaign-kpi-value campaign-kpi-value--info momo-mono">{{ current_stats.get('new', 0) | number_format }}</div>
                </div>
                <div class="campaign-kpi">
                    <div class="campaign-kpi-label">漲價</div>
                    <div class="campaign-kpi-value campaign-kpi-value--danger momo-mono">{{ current_stats.get('up', 0) | number_format }}</div>
                </div>
                <div class="campaign-kpi">
                    <div class="campaign-kpi-label">降價</div>
                    <div class="campaign-kpi-value campaign-kpi-value--success momo-mono">{{ current_stats.get('down', 0) | number_format }}</div>
                </div>
            </div>
            <div class="campaign-panel-footer momo-mono">
                {% if latest_run %}
                    <span class="momo-live-dot"></span>
                    <span>排程 · {{ latest_run.last_run }}</span>
                    <span>|</span>
                    <span>異動 {{ latest_run.get('changed_records', 0) }} 筆</span>
                {% else %}
                    <span>尚無排程紀錄</span>
                {% endif %}
            </div>
        </aside>
    </section>

    <section>
        <div class="campaign-section-label">
            <span class="num momo-mono">02</span>
            <span class="title">時段</span>
        </div>
        {% if slot_stats %}
            <div class="campaign-slot-tabs" role="tablist">
                {% for slot, stats in slot_stats.items() %}
                    {% set slot_id = slugify(slot) %}
                    <a class="campaign-slot-tab {% if slot == active_tab %}active{% endif %}" id="slot-{{ slot_id }}-tab" href="{{ url_for(current_endpoint, slot=slot, sort_by=current_sort, order=current_order, page=1, per_page=page_window.per_page) }}" role="tab" aria-selected="{{ 'true' if slot == active_tab else 'false' }}">
                        <span class="momo-mono">{{ slot }}</span>
                        <span class="campaign-slot-count momo-mono">{{ stats.get('on_shelf', 0) }} 件</span>
                    </a>
                {% endfor %}
            </div>
        {% else %}
            <div class="campaign-table-card">
                <div class="campaign-empty">目前沒有可顯示的活動時段資料</div>
            </div>
        {% endif %}
    </section>

    {% if slot_stats %}
        <section class="tab-content">
            {% set slot = active_tab %}
            {% set stats = slot_stats.get(slot, {'new': 0, 'up': 0, 'down': 0, 'delisted_last_run': 0, 'on_shelf': 0}) %}
            {% set slot_id = slugify(slot) %}
            {% set items = grouped_items.get(slot, []) %}
                <div class="tab-pane fade {% if slot == active_tab %}show active{% endif %}" id="slot-{{ slot_id }}" role="tabpanel">
                    <div class="campaign-table-card">
                        <div class="campaign-table-head">
                            <span class="campaign-section-index momo-mono">03</span>
                            <strong>商品列表</strong>
                            <span class="campaign-visible-count momo-mono" data-campaign-visible-count>
                                {{ page_window.start_item }}-{{ page_window.end_item }} / {{ page_window.total_items }} 筆
                            </span>
                            <div class="campaign-filterbar" aria-label="{{ slot }} 商品狀態篩選">
                                <button class="campaign-filter-chip is-active" type="button" data-campaign-filter="all">本頁 {{ items|length }}</button>
                                <button class="campaign-filter-chip" type="button" data-campaign-filter="new">新品 {{ stats.get('new', 0) }}</button>
                                <button class="campaign-filter-chip" type="button" data-campaign-filter="up">漲價 {{ stats.get('up', 0) }}</button>
                                <button class="campaign-filter-chip" type="button" data-campaign-filter="down">降價 {{ stats.get('down', 0) }}</button>
                                <button class="campaign-filter-chip" type="button" data-campaign-filter="delisted">下架 {{ stats.get('delisted_last_run', 0) }}</button>
                            </div>
                            <nav class="campaign-pagination" aria-label="{{ slot }} 商品分頁">
                                <a class="campaign-page-link" href="{{ url_for(current_endpoint, slot=active_tab, sort_by=current_sort, order=current_order, page=page_window.page - 1, per_page=page_window.per_page) }}" aria-disabled="{{ 'false' if page_window.has_prev else 'true' }}">
                                    <i class="fas fa-chevron-left" aria-hidden="true"></i>
                                    <span>上一頁</span>
                                </a>
                                <span>第 {{ page_window.page }} / {{ page_window.total_pages }} 頁</span>
                                <a class="campaign-page-link" href="{{ url_for(current_endpoint, slot=active_tab, sort_by=current_sort, order=current_order, page=page_window.page + 1, per_page=page_window.per_page) }}" aria-disabled="{{ 'false' if page_window.has_next else 'true' }}">
                                    <span>下一頁</span>
                                    <i class="fas fa-chevron-right" aria-hidden="true"></i>
                                </a>
                            </nav>
                        </div>
                        <div class="campaign-table-wrap">
                            <table class="campaign-table">
                                <thead>
                                    <tr>
                                        <th>分類 / 狀態</th>
                                        <th>
                                            {% set next_order_name = 'asc' if current_sort == 'name' and current_order == 'desc' else 'desc' %}
                                            <a href="{{ url_for(current_endpoint, slot=active_tab, sort_by='name', order=next_order_name, page=1, per_page=page_window.per_page) }}">商品資訊</a>
                                        </th>
                                        <th class="text-end">
                                            {% set next_order_price = 'asc' if current_sort == 'price' and current_order == 'desc' else 'desc' %}
                                            <a href="{{ url_for(current_endpoint, slot=active_tab, sort_by='price', order=next_order_price, page=1, per_page=page_window.per_page) }}">價格</a>
                                        </th>
                                        <th class="text-center">
                                            {% if current_promo_page == 'edm' %}
                                                {% set next_order_qty = 'asc' if current_sort == 'remain_qty' and current_order == 'desc' else 'desc' %}
                                                <a href="{{ url_for(current_endpoint, slot=active_tab, sort_by='remain_qty', order=next_order_qty, page=1, per_page=page_window.per_page) }}">銷售 / 庫存</a>
                                            {% else %}
                                                狀態
                                            {% endif %}
                                        </th>
                                        <th>追蹤資訊</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for item in items %}
                                        {% set campaign_filter = 'new' if item.status_change == 'NEW' else ('up' if item.status_change == 'PRICE_UP' else ('down' if item.status_change == 'PRICE_DOWN' else ('delisted' if item.status_change in ['DELISTED', 'SLOT_END'] else 'active'))) %}
                                        <tr class="campaign-row" data-campaign-row data-campaign-filter="{{ campaign_filter }}" data-i-code="{{ item.i_code }}">
                                            <td>
                                                <span class="campaign-category">{{ item.main_category or '未分類' }}</span>
                                            </td>
                                            <td>
                                                <div class="campaign-product-cell">
                                                    {% if item.image_url %}
                                                        <img class="campaign-product-thumb" src="{{ item.image_url }}" alt="{{ item.name }}" width="52" height="52" loading="lazy" decoding="async" referrerpolicy="no-referrer">
                                                    {% else %}
                                                        <div class="campaign-product-thumb campaign-product-thumb--empty">無圖</div>
                                                    {% endif %}
                                                    <div>
                                                        <a class="campaign-product-name momo-tracked-link" href="{{ item.safe_product_url or '#' }}" target="_blank" rel="noopener noreferrer" data-momo-original-url="{{ item.safe_product_url or '#' }}"
                                                            data-track-platform="momo"
                                                            data-track-source="edm-dashboard-v2-table"
                                                            data-track-product-id="{{ item.i_code }}"
                                                            data-track-icode="{{ item.i_code }}"
                                                            data-track-product-name="{{ item.name|e }}">{{ item.name }}</a>
                                                        <button
                                                            class="campaign-product-id"
                                                            type="button"
                                                            data-campaign-copy="{{ item.i_code }}"
                                                            title="複製 MOMO 商品 ID"
                                                        >
                                                            MOMO {{ item.i_code }} <i class="far fa-copy" aria-hidden="true"></i>
                                                        </button>
                                                        <div class="campaign-product-meta">
                                                            {% if item.status_change == 'NEW' %}
                                                                <span class="campaign-badge">NEW</span>
                                                            {% elif item.status_change == 'PRICE_DOWN' %}
                                                                <span class="campaign-badge campaign-badge--success">降價</span>
                                                            {% elif item.status_change == 'PRICE_UP' %}
                                                                <span class="campaign-badge campaign-badge--danger">漲價</span>
                                                            {% elif item.status_change in ['DELISTED', 'SLOT_END'] %}
                                                                <span class="campaign-badge">下架</span>
                                                            {% endif %}
                                                            {% if item.discount_text %}
                                                                <span class="campaign-badge">{{ item.discount_text }}</span>
                                                            {% endif %}
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td class="text-end momo-mono">
                                                {% if item.previous_price and item.price and item.previous_price != item.price %}
                                                    {% set diff = item.price - item.previous_price %}
                                                    {% set percent = ((diff|abs) / item.previous_price * 100) | round(1) %}
                                                    {% if diff < 0 %}
                                                        <div class="campaign-change-down">▼ {{ (diff|abs) | number_format }}<span class="campaign-change-pct">{{ percent }}%</span></div>
                                                    {% else %}
                                                        <div class="campaign-change-up">▲ {{ diff | number_format }}<span class="campaign-change-pct">{{ percent }}%</span></div>
                                                    {% endif %}
                                                    <div><span class="campaign-old-price">${{ item.previous_price | number_format }}</span></div>
                                                    <button
                                                        class="campaign-history-button"
                                                        type="button"
                                                        data-campaign-history-trigger
                                                        data-i-code="{{ item.i_code }}"
                                                        data-product-name="{{ item.name|e }}"
                                                        aria-label="查看價格歷史圖表"
                                                    >
                                                        <span class="campaign-price">${{ item.price | number_format }}</span>
                                                        <i class="fas fa-chart-line" aria-hidden="true"></i>
                                                    </button>
                                                {% elif item.price is not none %}
                                                    <button
                                                        class="campaign-history-button"
                                                        type="button"
                                                        data-campaign-history-trigger
                                                        data-i-code="{{ item.i_code }}"
                                                        data-product-name="{{ item.name|e }}"
                                                        aria-label="查看價格歷史圖表"
                                                    >
                                                        <span class="campaign-price">${{ item.price | number_format }}</span>
                                                        <i class="fas fa-chart-line" aria-hidden="true"></i>
                                                    </button>
                                                {% else %}
                                                    <span class="campaign-muted-placeholder">--</span>
                                                {% endif %}
                                            </td>
                                            <td class="text-center momo-mono">
                                                {% if current_promo_page == 'edm' %}
                                                    <div class="campaign-sales-stack">
                                                        {% if item.remain_qty is not none %}
                                                            <div class="campaign-sales-main">剩 {{ item.remain_qty | number_format }} 組</div>
                                                        {% else %}
                                                            <div class="campaign-sales-main campaign-sales-main--muted">--</div>
                                                        {% endif %}
                                                        <div class="campaign-sales-sub">已售 {{ item.total_sold | default(0) | number_format }} 組</div>
                                                        {% if item.qty_history and item.qty_history|length > 1 %}
                                                            {% set tooltip_content %}
                                                                <div class='text-start p-1'>
                                                                    <strong>當日銷售歷程</strong><br>
                                                                    {% for h in item.qty_history %}
                                                                        <small>{{ h.time }}</small> &nbsp; 剩 {{ h.qty }} 組<br>
                                                                    {% endfor %}
                                                                </div>
                                                            {% endset %}
                                                            <button
                                                                class="campaign-tooltip-trigger"
                                                                type="button"
                                                                data-bs-toggle="tooltip"
                                                                data-bs-html="true"
                                                                title="{{ tooltip_content }}"
                                                            >銷售歷程</button>
                                                        {% endif %}
                                                    </div>
                                                {% else %}
                                                    <span class="campaign-badge">{{ item.status_change or '活動中' }}</span>
                                                {% endif %}
                                            </td>
                                            <td class="momo-mono">
                                                <div class="campaign-track-stack">
                                                    <div class="campaign-track-line">上架 {{ item.days_on_shelf | default(1) }} 天</div>
                                                    <div class="campaign-track-line">時段 {{ item.time_slot or slot }}</div>
                                                    <div class="campaign-track-line">
                                                        {% if item.crawled_at %}
                                                            {{ item.crawled_at.strftime('%m/%d %H:%M') }}
                                                        {% else %}
                                                            --
                                                        {% endif %}
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                    {% else %}
                                        <tr>
                                            <td colspan="5">
                                                <div class="campaign-empty">此時段目前沒有商品資料</div>
                                            </td>
                                        </tr>
                                    {% endfor %}
                                    <tr class="campaign-filter-empty is-hidden">
                                        <td colspan="5">
                                            <div class="campaign-empty">此篩選條件目前沒有商品資料</div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
        </section>
    {% endif %}
</div>

<div class="modal fade campaign-history-modal" id="campaignHistoryModal" tabindex="-1" aria-labelledby="campaignHistoryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <div>
                    <h5 class="modal-title" id="campaignHistoryModalLabel">歷史價格走勢</h5>
                    <div class="campaign-history-subtitle momo-mono" id="campaignHistoryModalSubtitle">真實價格紀錄</div>
                    <div class="campaign-history-range" aria-label="價格歷史區間">
                        <button type="button" data-campaign-history-range="week">週</button>
                        <button class="is-active" type="button" data-campaign-history-range="month">月</button>
                        <button type="button" data-campaign-history-range="quarter">季</button>
                        <button type="button" data-campaign-history-range="year">年</button>
                    </div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="關閉"></button>
            </div>
            <div class="modal-body">
                <div class="campaign-chart-shell">
                    <div class="campaign-chart-state" id="campaignHistoryChartState">載入價格歷史中...</div>
                    <canvas class="campaign-chart-canvas is-hidden" id="campaignPriceChart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="{{ url_for('static', filename='js/analysis-chart-theme.js') }}"></script>
<script src="{{ url_for('static', filename='js/page-edm-v2.js') }}"></script>
{% endblock %}
