/* Dashboard V2 page interactions extracted from dashboard_v2.html. */
let priceChartInstance = null;
    let activeHistoryRange = 'month';
    let currentHistoryProductId = null;
    let currentHistoryProductName = '';
    let dashboardChartLoader = null;

    function getCSRFToken() {
        return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    }

    function formatPriceTick(value) {
        return '$' + Number(value || 0).toLocaleString();
    }

    function setHistoryChartState(message, showCanvas = false) {
        const state = document.getElementById('historyChartState');
        const canvas = document.getElementById('priceChart');
        if (!state || !canvas) return;
        state.textContent = message;
        state.classList.toggle('is-hidden', showCanvas);
        canvas.classList.toggle('is-hidden', !showCanvas);
    }

    function destroyHistoryChart() {
        if (priceChartInstance) {
            priceChartInstance.destroy();
            priceChartInstance = null;
        }
    }

    function ensureDashboardChart() {
        if (window.EwoooCChartTheme && window.EwoooCChartTheme.loadChartJs) {
            return window.EwoooCChartTheme.loadChartJs();
        }
        if (typeof Chart !== 'undefined') {
            return Promise.resolve(window.Chart);
        }
        if (dashboardChartLoader) {
            return dashboardChartLoader;
        }
        dashboardChartLoader = new Promise((resolve, reject) => {
            const existing = document.querySelector('script[data-chartjs-loader="dashboard"]');
            if (existing) {
                existing.addEventListener('load', () => resolve(window.Chart), { once: true });
                existing.addEventListener('error', () => reject(new Error('Chart.js 載入失敗')), { once: true });
                return;
            }
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js';
            script.async = true;
            script.dataset.chartjsLoader = 'dashboard';
            script.onload = () => resolve(window.Chart);
            script.onerror = () => reject(new Error('Chart.js 載入失敗'));
            document.head.appendChild(script);
        });
        return dashboardChartLoader;
    }

    function updateHistoryRangeButtons() {
        document.querySelectorAll('[data-history-range]').forEach(button => {
            button.classList.toggle('is-active', button.dataset.historyRange === activeHistoryRange);
        });
    }

    function showHistory(productId, productName, range = activeHistoryRange) {
        const modalEl = document.getElementById('historyModal');
        const title = document.getElementById('historyModalLabel');
        const subtitle = document.getElementById('historyModalSubtitle');
        const canvas = document.getElementById('priceChart');

        if (!modalEl || !title || !subtitle || !canvas) return;

        currentHistoryProductId = productId;
        currentHistoryProductName = productName || '歷史價格走勢';
        activeHistoryRange = range;
        updateHistoryRangeButtons();

        title.textContent = productName || '歷史價格走勢';
        subtitle.textContent = `商品 ID ${productId} · 讀取真實價格紀錄`;
        destroyHistoryChart();
        setHistoryChartState('載入價格歷史中...');

        const modal = bootstrap.Modal.getOrCreateInstance(modalEl);
        modal.show();

        ensureDashboardChart()
            .then(() => fetch(`/api/history/${productId}?range=${activeHistoryRange}&format=v2`))
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                const series = Array.isArray(data) ? { momo: data, pchome: [] } : (data.series || {});
                const momoPoints = Array.isArray(series.momo) ? series.momo : (Array.isArray(data.data) ? data.data : []);
                const pchomePoints = Array.isArray(series.pchome) ? series.pchome : [];
                const rangeLabel = Array.isArray(data) ? '' : (data.range_label || '');
                if (rangeLabel) {
                    const pchomeNote = pchomePoints.length > 0 ? ' · 含 PChome 歷史快照' : '';
                    subtitle.textContent = `商品 ID ${productId} · ${rangeLabel}真實價格紀錄${pchomeNote}`;
                }

                if (momoPoints.length === 0 && pchomePoints.length === 0) {
                    setHistoryChartState('目前沒有可顯示的歷史價格紀錄。');
                    return;
                }

                setHistoryChartState('', true);
                const ctx = canvas.getContext('2d');
                const momoGradient = ctx.createLinearGradient(0, 0, 0, 380);
                momoGradient.addColorStop(0, 'rgba(190, 106, 45, 0.26)');
                momoGradient.addColorStop(1, 'rgba(190, 106, 45, 0.04)');
                const pchomeGradient = ctx.createLinearGradient(0, 0, 0, 380);
                pchomeGradient.addColorStop(0, 'rgba(70, 127, 181, 0.18)');
                pchomeGradient.addColorStop(1, 'rgba(70, 127, 181, 0.03)');
                const labels = Array.from(new Set([
                    ...momoPoints.map(point => point.t),
                    ...pchomePoints.map(point => point.t)
                ])).sort();
                const toPriceMap = points => points.reduce((acc, point) => {
                    acc[point.t] = point.p;
                    return acc;
                }, {});
                const momoMap = toPriceMap(momoPoints);
                const pchomeMap = toPriceMap(pchomePoints);
                const datasets = [{
                    label: 'MOMO',
                    data: labels.map(label => momoMap[label] ?? null),
                    borderColor: '#be6a2d',
                    backgroundColor: momoGradient,
                    borderWidth: 3,
                    fill: true,
                    tension: 0.35,
                    spanGaps: true,
                    pointRadius: 3,
                    pointHoverRadius: 7,
                    pointBackgroundColor: '#be6a2d',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2
                }];
                if (pchomePoints.length > 0) {
                    datasets.push({
                        label: 'PChome',
                        data: labels.map(label => pchomeMap[label] ?? null),
                        borderColor: '#467fb5',
                        backgroundColor: pchomeGradient,
                        borderWidth: 2,
                        fill: false,
                        tension: 0.28,
                        spanGaps: true,
                        pointRadius: 3,
                        pointHoverRadius: 7,
                        pointBackgroundColor: '#467fb5',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2
                    });
                }

                priceChartInstance = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels,
                        datasets
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        interaction: {
                            mode: 'index',
                            intersect: false
                        },
                        plugins: {
                            legend: {
                                display: pchomePoints.length > 0,
                                labels: {
                                    color: '#6d604f',
                                    usePointStyle: true,
                                    boxWidth: 8,
                                    boxHeight: 8
                                }
                            },
                            tooltip: {
                                backgroundColor: 'rgba(55, 45, 35, 0.94)',
                                titleColor: '#faf7f0',
                                bodyColor: '#faf7f0',
                                borderColor: '#be6a2d',
                                borderWidth: 1,
                                displayColors: true,
                                padding: 12,
                                callbacks: {
                                    label: context => `${context.dataset.label} ${formatPriceTick(context.parsed.y)}`
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: false,
                                grid: {
                                    color: 'rgba(71, 61, 49, 0.08)'
                                },
                                ticks: {
                                    color: '#7f715f',
                                    callback: formatPriceTick
                                }
                            },
                            x: {
                                grid: { display: false },
                                ticks: {
                                    color: '#9b8a77',
                                    maxRotation: 0,
                                    autoSkip: true,
                                    maxTicksLimit: 8
                                }
                            }
                        }
                    }
                });
            })
            .catch(error => {
                console.error('圖表載入失敗:', error);
                setHistoryChartState('價格歷史載入失敗，請稍後再試。');
            });
    }

    document.querySelectorAll('.dashboard-table tbody tr[data-product-id]').forEach(row => {
        row.addEventListener('click', event => {
            if (event.target.closest('a, button, [data-pchome-review-action]')) return;
            showHistory(row.dataset.productId, row.dataset.productName);
        });
    });

    document.querySelectorAll('[data-history-trigger]').forEach(button => {
        button.addEventListener('click', event => {
            event.stopPropagation();
            showHistory(button.dataset.productId, button.dataset.productName);
        });
    });

    document.querySelectorAll('[data-history-range]').forEach(button => {
        button.addEventListener('click', () => {
            if (!currentHistoryProductId) return;
            showHistory(currentHistoryProductId, currentHistoryProductName, button.dataset.historyRange);
        });
    });

    document.querySelectorAll('[data-dashboard-auto-submit]').forEach(select => {
        select.addEventListener('change', () => {
            if (select.form) {
                select.form.submit();
            }
        });
    });

    const dashboardTaskMap = {
        crawler: {
            confirmText: '確定要手動執行全站爬蟲嗎？可能需要一段時間。',
            url: '/api/run_task'
        },
        notification: {
            confirmText: '確定要發送今日商品異動通知嗎？',
            url: '/api/trigger_momo_notification'
        }
    };

    function runDashboardTask(taskName) {
        const task = dashboardTaskMap[taskName];
        if (!task || !confirm(task.confirmText)) return;
        fetch(task.url, {
            method: 'POST',
            headers: { 'X-CSRFToken': getCSRFToken() }
        })
            .then(response => response.json())
            .then(data => alert(data.message))
            .catch(error => alert('錯誤: ' + error));
    }

    document.querySelectorAll('[data-dashboard-task]').forEach(button => {
        button.addEventListener('click', () => runDashboardTask(button.dataset.dashboardTask));
    });

    let pchomeBackfillPollTimer = null;

    function getPchomeBackfillElements() {
        const card = document.querySelector('[data-pchome-backfill-card]');
        return {
            card,
            trigger: document.querySelector('[data-pchome-backfill-trigger]'),
            status: document.querySelector('[data-pchome-backfill-status]'),
            result: document.querySelector('[data-pchome-backfill-result]'),
            progress: document.querySelector('[data-pchome-backfill-progress]'),
            backfillEndpoint: card ? card.dataset.backfillEndpoint : '/api/ai/pchome-match/backfill',
            statusEndpoint: card ? card.dataset.statusEndpoint : '/api/ai/pchome-match/backfill/status'
        };
    }

    function formatBackfillCount(value) {
        return Number(value || 0).toLocaleString();
    }

    function schedulePchomeBackfillPoll() {
        if (pchomeBackfillPollTimer) {
            clearTimeout(pchomeBackfillPollTimer);
        }
        pchomeBackfillPollTimer = setTimeout(loadPchomeBackfillStatus, 5000);
    }

    function renderPchomeBackfillStatus(payload) {
        const status = payload && payload.data ? payload.data : (payload || {});
        const elements = getPchomeBackfillElements();
        if (!elements.card) return;

        const currentRun = status.current_run || {};
        const result = currentRun.result || status.last_result || {};
        const pickResult = currentRun.pick_result || {};
        const running = Boolean(status.running || currentRun.running);
        const progressPct = Math.max(0, Math.min(Number(status.progress_pct || currentRun.progress_pct || 0), 100));
        const statusKey = status.status || currentRun.status || 'idle';
        const stageLabel = status.stage_label || currentRun.stage_label || '尚未執行';
        const updatedAt = status.updated_at || currentRun.updated_at || currentRun.finished_at || '';

        elements.card.dataset.status = statusKey;
        if (elements.progress) {
            elements.progress.style.width = `${progressPct}%`;
        }
        if (elements.status) {
            elements.status.textContent = updatedAt ? `${stageLabel} · ${updatedAt}` : stageLabel;
        }
        if (elements.result) {
            if (status.last_error || currentRun.last_error) {
                elements.result.textContent = status.last_error || currentRun.last_error;
            } else if (result && Object.keys(result).length > 0) {
                const pickWritten = pickResult.written !== undefined ? ` · 挑品 ${formatBackfillCount(pickResult.written)}` : '';
                elements.result.textContent = (
                    `比對 ${formatBackfillCount(result.total_skus)} · 成功 ${formatBackfillCount(result.matched)}`
                    + ` · 待覆核 ${formatBackfillCount(result.skipped_low_score)}`
                    + ` · 無結果 ${formatBackfillCount(result.skipped_no_result)}`
                    + pickWritten
                );
            } else {
                elements.result.textContent = running ? '正在累積結果' : '尚無最近結果';
            }
        }
        if (elements.trigger) {
            elements.trigger.disabled = running;
            elements.trigger.classList.toggle('is-loading', running);
            elements.trigger.innerHTML = running
                ? '<i class="fas fa-spinner fa-spin"></i> 補抓中'
                : '<i class="fas fa-search"></i> 補抓 60 筆';
        }

        if (running) {
            schedulePchomeBackfillPoll();
        } else if (pchomeBackfillPollTimer) {
            clearTimeout(pchomeBackfillPollTimer);
            pchomeBackfillPollTimer = null;
        }
    }

    function loadPchomeBackfillStatus() {
        const elements = getPchomeBackfillElements();
        if (!elements.card) return Promise.resolve();
        return fetch(elements.statusEndpoint, {
            headers: { 'Accept': 'application/json' }
        })
            .then(response => response.json())
            .then(renderPchomeBackfillStatus)
            .catch(error => {
                console.warn('[DashboardV2] PChome backfill status load failed:', error);
                if (elements.status) {
                    elements.status.textContent = '狀態讀取失敗';
                }
            });
    }

    function backfillPchomeMatches() {
        const elements = getPchomeBackfillElements();
        if (!elements.card || !elements.trigger) return;
        const limit = Number(elements.trigger.dataset.limit || 60);
        if (!confirm(`啟動 PChome 待比對補抓 ${limit} 筆？`)) return;

        elements.trigger.disabled = true;
        if (elements.status) {
            elements.status.textContent = '正在送出補抓任務';
        }
        fetch(elements.backfillEndpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            },
            body: JSON.stringify({ limit })
        })
            .then(response => response.json().then(data => ({ ok: response.ok, status: response.status, data })))
            .then(({ ok, status, data }) => {
                renderPchomeBackfillStatus(data);
                if (!ok && status !== 409) {
                    throw new Error(data.message || data.error || 'PChome 補抓啟動失敗');
                }
                schedulePchomeBackfillPoll();
            })
            .catch(error => {
                if (elements.status) {
                    elements.status.textContent = error.message || 'PChome 補抓啟動失敗';
                }
                if (elements.trigger) {
                    elements.trigger.disabled = false;
                }
            });
    }

    window.backfillPchomeMatches = backfillPchomeMatches;
    document.querySelectorAll('[data-pchome-backfill-trigger]').forEach(button => {
        button.addEventListener('click', backfillPchomeMatches);
    });
    loadPchomeBackfillStatus();

    function runPchomeReviewDecision(button) {
        const sku = button.dataset.reviewSku || '';
        const action = button.dataset.reviewAction || '';
        if (!sku || !action) return;
        const confirmText = button.dataset.reviewConfirm || '確認寫入這筆覆核決策？';
        if (!confirm(confirmText)) return;
        const reason = prompt('補充覆核原因（可留空）', '') || '';
        const originalText = button.textContent;
        button.disabled = true;
        button.textContent = '寫入中';
        fetch(`/api/pchome-review/${encodeURIComponent(sku)}/decision`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            },
            body: JSON.stringify({ action, reason })
        })
            .then(response => response.json().then(data => ({ ok: response.ok, data })))
            .then(({ ok, data }) => {
                if (!ok || !data.success) {
                    throw new Error(data.message || '覆核寫入失敗');
                }
                alert(data.message || '覆核已寫入');
                window.location.reload();
            })
            .catch(error => {
                alert('錯誤: ' + error.message);
                button.disabled = false;
                button.textContent = originalText;
            });
    }

    document.querySelectorAll('[data-pchome-review-action]').forEach(button => {
        button.addEventListener('click', event => {
            event.stopPropagation();
            runPchomeReviewDecision(button);
        });
    });

        function trackMomoLinkClick(event) {
            const link = event.target.closest('.momo-tracked-link');
            if (!link) {
                return;
            }

        const href = link.getAttribute('href') || '';
        const originalHref = link.dataset.momoOriginalUrl || href;
        if (!href || href === '#') {
            return;
        }

        const isBlocked = isBlockedMomoUrl(href);

        const payload = {
            url: originalHref,
            page: location.pathname,
            source: link.dataset.trackSource || 'unknown',
            platform: link.dataset.trackPlatform || 'momo',
            product_id: link.dataset.trackProductId || '',
            i_code: link.dataset.trackIcode || '',
            product_name: link.dataset.trackProductName || '',
            label: (link.textContent || '').trim(),
            effective_url: href
        };

        if (isBlocked) {
            console.warn('[DashboardV2] 嘗試打開 MOMO 404 網址', payload);
            event.preventDefault();

            const fallbackUrl = link.dataset.momoFallbackUrl || getSafeMomoFallbackUrl(link);
            if (fallbackUrl && fallbackUrl !== '#' && fallbackUrl !== href) {
                link.dataset.momoFallbackUrl = fallbackUrl;
                link.setAttribute('href', fallbackUrl);
                payload.effective_url = fallbackUrl;
                openMomoUrl(link, fallbackUrl);
                fetch('/api/track_momo_link', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCSRFToken()
                    },
                    body: JSON.stringify(payload)
                }).catch(() => {});
                return;
            }
        }

        fetch('/api/track_momo_link', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            },
            body: JSON.stringify(payload)
        }).catch(() => {});
    }

        function getSafeMomoFallbackUrl(link) {
            const iCode = (link.dataset.trackIcode || link.dataset.trackProductId || '').trim();
            if (!isLikelyMomoProductCode(iCode)) {
                return '#';
            }
            return `https://www.momoshop.com.tw/goods/GoodsDetail.jsp?i_code=${encodeURIComponent(iCode)}`;
        }

        function openMomoUrl(link, url) {
            if (!url || url === '#') {
                return;
            }

            const target = (link.getAttribute('target') || '_self').toLowerCase();
            if (target === '_blank') {
                window.open(url, '_blank', 'noopener,noreferrer');
                return;
            }

            if (target === '_self' || target === '') {
                window.location.href = url;
                return;
            }

            window.open(url, target);
        }

        function isBlockedMomoUrl(url) {
            const lowered = (url || '').toLowerCase();
            if (lowered.includes('EC404.html') || lowered.includes('ec404')) {
                return true;
            }
            try {
                const parsed = new URL(url, location.origin);
                const path = (parsed.pathname || '').toLowerCase();
                if (!path.includes('goodsdetail')) {
                    return false;
                }
                const code = (parsed.searchParams.get('i_code') || '').trim();
                if (code) {
                    return !isLikelyMomoProductCode(code);
                }
                return !/\/goodsdetail\/[^/?#]+/i.test(path);
            } catch (error) {
                if (!/goodsdetail\.jsp/i.test(lowered)) {
                    return false;
                }
                const hasCode = /[?&]i_code=([^&#]+)/i.test(lowered);
                if (!hasCode) {
                    return true;
                }
                const match = /[?&]i_code=([^&#]+)/i.exec(lowered);
                const code = match ? (match[1] || '').trim() : '';
                return !isLikelyMomoProductCode(code);
            }
        }

        function isLikelyMomoProductCode(value) {
            const cleaned = (value || '').trim();
            if (!cleaned) {
                return false;
            }
            const lowered = cleaned.toLowerCase();
            if (lowered === 'nan' || lowered === 'none' || lowered === 'null' || lowered === 'undefined') {
                return false;
            }
            if (lowered.startsWith('momo_') || lowered.startsWith('manual_') || lowered.startsWith('pchome_')) {
                return false;
            }
            return /^[A-Za-z0-9_-]{4,}$/.test(cleaned);
        }

    document.addEventListener('click', trackMomoLinkClick);
