<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{% block title %}WOOO TECH{% endblock %}</title>

    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

    <!-- 共用樣式 -->
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            --bg-gradient: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%);
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: var(--bg-gradient);
            min-height: 100vh;
            padding-top: 70px;
        }

        /* 導航列樣式 */
        .navbar {
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        .navbar.bg-custom-dark {
            background: var(--primary-gradient) !important;
        }

        .navbar-dark .navbar-brand {
            color: #ffffff !important;
            font-weight: 600;
        }

        .navbar-dark .navbar-nav .nav-link {
            color: rgba(255, 255, 255, 0.9) !important;
            font-weight: 500;
            transition: all 0.3s;
        }

        .navbar-dark .navbar-nav .nav-link:hover {
            color: #ffffff !important;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 6px;
        }

        .navbar-dark .navbar-nav .nav-link.active {
            color: #ffffff !important;
            background: rgba(255, 255, 255, 0.15);
            border-radius: 6px;
            font-weight: 600;
        }

        .navbar-dark .navbar-text {
            color: rgba(255, 255, 255, 0.8) !important;
        }

        .dropdown-menu {
            border: none;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            border-radius: 8px;
        }

        .dropdown-item {
            padding: 0.5rem 1rem;
            transition: all 0.2s;
        }

        .dropdown-item:hover {
            background: #f8f9fa;
        }

        /* 使用者下拉選單 */
        .user-dropdown .dropdown-toggle::after {
            display: none;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: rgba(255,255,255,0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
        }

        /* 頁面標題區塊 */
        .page-header {
            background: white;
            padding: 1.5rem 2rem;
            border-radius: 16px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.06);
            margin-bottom: 1.5rem;
        }

        .page-header h1 {
            font-size: 1.75rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .page-header p {
            color: #6c757d;
            font-size: 0.95rem;
            margin-bottom: 0;
        }

        /* 卡片樣式 */
        .card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.08);
        }

        /* 按鈕樣式 */
        .btn {
            border-radius: 8px;
            font-weight: 500;
        }

        /* Toast 通知 */
        .toast-container {
            z-index: 9999;
        }
    </style>

    {% block extra_css %}{% endblock %}
</head>
<body>
    <!-- 導航列 -->
    {% include 'components/_navbar.html' %}

    <!-- WOOO 載入動畫 (可選：透過 block 控制是否顯示) -->
    {% block loading_overlay %}
    {% include 'components/_loading.html' %}
    {% endblock %}

    <!-- 主要內容 -->
    <main class="{% block main_class %}container-fluid{% endblock %}" style="padding: 1.5rem;">
        {% block content %}{% endblock %}
    </main>

    <!-- 頁尾 (可選) -->
    {% block footer %}{% endblock %}

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

    <!-- MOMO 404 防呆攔截：避免自動打開 EC404 頁面 -->
    <script>
        (function () {
            if (window.__momoLinkGuardInstalled) {
                return;
            }
            window.__momoLinkGuardInstalled = true;

            const MOMO_HOSTS = new Set(['www.momoshop.com.tw', 'm.momoshop.com.tw']);
            const MOMO_CODE_RE = /^[A-Za-z0-9_-]{4,}$/;

            const toText = value => (value == null ? '' : String(value));

            const hasMomoHost = function (url) {
                const target = toText(url).trim();
                if (!target) {
                    return false;
                }
                try {
                    const parsed = new URL(target, location.origin);
                    return MOMO_HOSTS.has((parsed.hostname || '').toLowerCase());
                } catch (error) {
                    return /(^|\/)m(?:\.momoshop\.com\.tw|\.momoshop\.com\.tw)(\/|$)|www\.momoshop\.com\.tw/i.test(target);
                }
            };

            const isBlockedMomoUrl = function (url) {
                const lowered = toText(url).toLowerCase();
                if (lowered.includes('ec404.html') || lowered.includes('/ecm/js/err404/')) {
                    return true;
                }

                try {
                    const parsed = new URL(url, location.origin);
                    const path = (parsed.pathname || '').toLowerCase();
                    if (!path.includes('goodsdetail')) {
                        return false;
                    }
                    const iCode = (parsed.searchParams.get('i_code') || '').trim();
                    if (iCode) {
                        return !isLikelyMomoIcode(iCode);
                    }
                    return !/\/goodsdetail\/[^/?#]+/i.test(path);
                } catch (error) {
                    const hasGoodsDetail = /goodsdetail\.jsp/i.test(lowered);
                    if (!hasGoodsDetail) {
                        return false;
                    }
                    const hasIcode = /[?&]i_code=([^&#]+)/i.test(lowered);
                    if (!hasIcode) {
                        return true;
                    }
                    const match = /[?&]i_code=([^&#]+)/i.exec(lowered);
                    const extracted = match ? (match[1] || '').trim() : '';
                    return !isLikelyMomoIcode(extracted);
                }
            };

            const isLikelyMomoIcode = function (value) {
                const cleaned = toText(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_')) {
                    return false;
                }
                return MOMO_CODE_RE.test(cleaned);
            };

            const getIcodeFromUrl = function (url) {
                const target = toText(url).trim();
                if (!target) {
                    return '';
                }

                try {
                    const parsed = new URL(target, location.origin);
                    const iCode = parsed.searchParams.get('i_code');
                    if (iCode) {
                        return iCode.trim();
                    }
                } catch (error) {
                    // ignore
                }

                const match = /[?&]i_code=([^&#]+)/i.exec(target);
                return match ? decodeURIComponent(match[1] || '').trim() : '';
            };

            const buildSafeMomoUrl = function (iCode) {
                const cleaned = toText(iCode).trim();
                if (!isLikelyMomoIcode(cleaned)) {
                    return '';
                }
                return `https://www.momoshop.com.tw/goods/GoodsDetail.jsp?i_code=${encodeURIComponent(cleaned)}`;
            };

            const resolveSafeUrl = function (link, href) {
                const original = toText(link.dataset && link.dataset.momoOriginalUrl).trim();
                const explicit = toText(link.dataset && (link.dataset.trackIcode || link.dataset.trackProductId)).trim();
                const fallbackCode = explicit || getIcodeFromUrl(original) || getIcodeFromUrl(href);

                if (fallbackCode) {
                    return buildSafeMomoUrl(fallbackCode);
                }
                return '#';
            };

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

                const target = toText(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);
            };

            const trackMomoLink = function (payload) {
                const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
                const body = {
                    status: 'tracked',
                    ...payload
                };

                const headers = {
                    'Content-Type': 'application/json'
                };
                if (csrfToken) {
                    headers['X-CSRFToken'] = csrfToken;
                }

                fetch('/api/track_momo_link', {
                    method: 'POST',
                    headers,
                    body: JSON.stringify(body),
                    keepalive: true
                }).catch(() => {});
            };

            const guardMomoLink = function (event) {
                if (event.defaultPrevented) {
                    return;
                }

                if (event.type === 'click' && event.button && event.button !== 0) {
                    return;
                }
                if (event.type === 'auxclick' && event.button !== 1) {
                    return;
                }

                const link = event.target.closest ? event.target.closest('a') : null;
                if (!link) {
                    return;
                }

                const href = toText(link.getAttribute('href') || '').trim();
                if (!href || href === '#') {
                    return;
                }

                const isTrackedClass = link.classList && link.classList.contains('momo-tracked-link');
                const raw = toText(link.getAttribute('href') || '').trim();
                const original = toText(link.dataset && link.dataset.momoOriginalUrl).trim();
                if (!isTrackedClass && !hasMomoHost(raw) && !hasMomoHost(original)) {
                    return;
                }

                const blocked = isBlockedMomoUrl(href) || isBlockedMomoUrl(original);
                const payload = {
                    url: original || href,
                    page: location.pathname,
                    source: toText(link.dataset && link.dataset.trackSource) || 'auto-guard',
                    platform: toText(link.dataset && link.dataset.trackPlatform) || 'momo',
                    product_id: toText(link.dataset && link.dataset.trackProductId) || '',
                    i_code: toText(link.dataset && link.dataset.trackIcode) || '',
                    product_name: toText(link.dataset && link.dataset.trackProductName) || '',
                    label: toText(link.textContent || '').trim(),
                    effective_url: href,
                    blocked: blocked
                };

                if (!blocked && !isTrackedClass) {
                    return;
                }

                if (blocked) {
                    event.preventDefault();

                    const safeUrl = resolveSafeUrl(link, href);
                    if (safeUrl && safeUrl !== href) {
                        link.setAttribute('href', safeUrl);
                        payload.effective_url = safeUrl;
                        openMomoUrl(link, safeUrl);
                    }

                    trackMomoLink(payload);
                    return;
                }

                trackMomoLink(payload);
            };

            document.addEventListener('click', guardMomoLink, true);
            document.addEventListener('auxclick', guardMomoLink, true);
        })();
    </script>

    <!-- 共用 JavaScript -->
    <script>
        // CSRF Token 設定 (供 AJAX 使用)
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');

        // 全域 fetch 設定
        const fetchWithCSRF = (url, options = {}) => {
            options.headers = {
                ...options.headers,
                'X-CSRFToken': csrfToken
            };
            return fetch(url, options);
        };

        // Toast 通知函數
        function showToast(message, type = 'info') {
            const toastContainer = document.getElementById('toast-container') || createToastContainer();
            const toastId = 'toast-' + Date.now();
            const bgClass = {
                'success': 'bg-success',
                'error': 'bg-danger',
                'warning': 'bg-warning',
                'info': 'bg-primary'
            }[type] || 'bg-primary';

            const toastHtml = `
                <div id="${toastId}" class="toast ${bgClass} text-white" role="alert">
                    <div class="toast-body d-flex align-items-center">
                        <span>${message}</span>
                        <button type="button" class="btn-close btn-close-white ms-auto" data-bs-dismiss="toast"></button>
                    </div>
                </div>
            `;
            toastContainer.insertAdjacentHTML('beforeend', toastHtml);

            const toastEl = document.getElementById(toastId);
            const toast = new bootstrap.Toast(toastEl, { delay: 3000 });
            toast.show();
            toastEl.addEventListener('hidden.bs.toast', () => toastEl.remove());
        }

        function createToastContainer() {
            const container = document.createElement('div');
            container.id = 'toast-container';
            container.className = 'toast-container position-fixed top-0 end-0 p-3';
            document.body.appendChild(container);
            return container;
        }
    </script>

    {% block extra_js %}{% endblock %}
</body>
</html>
