<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}AgomTradePro - 个人投研平台{% endblock %}</title>
    {% load static %}
    <!-- AgomTradePro Design Tokens -->
    <link rel="stylesheet" href="{% static 'css/design-tokens.css' %}">
    <link rel="stylesheet" href="{% static 'css/main.css' %}">

    <!-- Legacy CSS (will be phased out) -->
    <link rel="stylesheet" href="{% static 'css/components.css' %}">

    <!-- HTMX (本地) -->
    <script src="{% static 'vendor/js/htmx.min.js' %}"></script>

    <!-- Bootstrap Icons (本地) -->
    <link rel="stylesheet" href="{% static 'vendor/css/bootstrap-icons.css' %}">

    <!-- Flatpickr 日期选择器 (本地) -->
    <link rel="stylesheet" href="{% static 'vendor/css/flatpickr.min.css' %}">
    <script src="{% static 'vendor/js/flatpickr.min.js' %}"></script>
    <script src="{% static 'vendor/js/flatpickr.zh.js' %}"></script>

    <!-- SweetAlert2 确认框 (本地) -->
    <script src="{% static 'vendor/js/sweetalert2.all.min.js' %}"></script>

    <!-- Alpine.js (轻量级响应式框架, 本地) -->
    <script defer src="{% static 'vendor/js/alpine.min.js' %}"></script>

    <style>
        :root {
            --color-rise: {{ market_visuals.rise|default:"var(--color-error)" }};
            --color-fall: {{ market_visuals.fall|default:"var(--color-success)" }};
            --color-rise-soft: {{ market_visuals.rise_soft|default:"var(--color-error-light)" }};
            --color-fall-soft: {{ market_visuals.fall_soft|default:"var(--color-success-light)" }};
            --color-rise-strong: {{ market_visuals.rise_strong|default:"var(--color-error-dark)" }};
            --color-fall-strong: {{ market_visuals.fall_strong|default:"var(--color-success-dark)" }};
            --color-capital-inflow: {{ market_visuals.inflow|default:"var(--color-error)" }};
            --color-capital-outflow: {{ market_visuals.outflow|default:"var(--color-success)" }};
        }
    </style>

    {% block extra_css %}{% endblock %}

    <!-- Floating Widget CSS -->
    <link rel="stylesheet" href="{% static 'css/floating-widget.css' %}">
</head>
<body
    hx-ext="sse,remove-me,morph-swap"
    hx-indicator="#global-loader"
    data-market-color-convention="{{ market_visuals.convention|default:'cn_a_share' }}"
>
    <!-- 全局加载指示器 -->
    <div id="global-loader" class="global-loader" style="display: none;">
        <div class="loader-spinner"></div>
    </div>

    <!-- 顶部导航栏 - 系统级导航 -->
    <header class="header">
        <div class="header-container">
            <a href="/" class="header-logo">AgomTradePro</a>

            <nav class="top-nav">
                {% if user.is_authenticated %}
                <a href="{% url 'dashboard:index' %}" class="top-nav-item">系统首页</a>
                <a href="{% url 'decision-workspace' %}" class="top-nav-item">决策工作台</a>
                {% else %}
                <a href="{% url 'index' %}" class="top-nav-item">首页</a>
                {% endif %}

                <!-- 宏观环境：下拉菜单 -->
                <div class="dropdown">
                    <button type="button" class="top-nav-item dropdown-trigger" aria-haspopup="true" aria-expanded="false">宏观环境</button>
                    <div class="dropdown-menu">
                        <a href="{% url 'regime:dashboard' %}" class="dropdown-item">Regime判定</a>
                        <a href="{% url 'policy:workbench' %}" class="dropdown-item">政策/情绪/热点工作台</a>
                        {% if user.is_staff %}
                        <a href="{% url 'policy:rss-manage' %}" class="dropdown-item">RSS源管理</a>
                        {% endif %}
                        {% if user.is_staff %}
                        <div class="dropdown-divider"></div>
                        <a href="{% url 'macro:data' %}" class="dropdown-item">宏观数据</a>
                        <a href="{% url 'filter:dashboard' %}" class="dropdown-item">趋势滤波</a>
                        {% endif %}
                    </div>
                </div>

                <!-- 账户与执行：下拉菜单 -->
                {% if user.is_authenticated %}
                <div class="dropdown">
                    <button type="button" class="top-nav-item dropdown-trigger" aria-haspopup="true" aria-expanded="false">账户与执行</button>
                    <div class="dropdown-menu">
                        <div class="dropdown-section-title">执行链路</div>
                        <a href="{% url 'decision-workspace' %}" class="dropdown-item">
                            <i class="bi bi-kanban"></i> 决策工作台
                        </a>
                        <div class="dropdown-divider"></div>
                        <a href="{% url 'simulated_trading:my-accounts' %}" class="dropdown-item">
                            <i class="bi bi-wallet2"></i> 我的投资账户
                        </a>
                        <a href="{% url 'share:manage' %}" class="dropdown-item">
                            <i class="bi bi-share"></i> 账户分享
                        </a>
                        <a href="{% url 'account:profile' %}#positions" class="dropdown-item">
                            <i class="bi bi-briefcase"></i> 我的持仓
                        </a>
                        <a href="{% url 'audit:manual_trades' %}" class="dropdown-item">
                            <i class="bi bi-file-earmark-spreadsheet"></i> 手动交易复盘
                        </a>
                        {% if user.is_staff %}
                        <a href="{% url 'audit:reports' %}" class="dropdown-item">
                            <i class="bi bi-clipboard-data"></i> 审计归因报告
                        </a>
                        {% endif %}
                    </div>
                </div>

                <!-- 策略研究：下拉菜单 -->
                <div class="dropdown">
                    <button type="button" class="top-nav-item dropdown-trigger" aria-haspopup="true" aria-expanded="false">策略研究</button>
                    <div class="dropdown-menu">
                        <a href="{% url 'signal:manage' %}" class="dropdown-item">
                            <i class="bi bi-broadcast"></i> 投资信号
                        </a>
                        <a href="{% url 'strategy:list' %}" class="dropdown-item">
                            <i class="bi bi-diagram-3"></i> 策略管理
                        </a>
                        <a href="{% url 'backtest:list' %}" class="dropdown-item">
                            <i class="bi bi-flask"></i> 回测引擎
                        </a>
                        <div class="dropdown-divider"></div>
                        <a href="{% url 'equity:screen' %}" class="dropdown-item">
                            <i class="bi bi-graph-up-arrow"></i> 个股筛选
                        </a>
                        <a href="{% url 'dashboard:alpha_ranking' %}" class="dropdown-item">
                            <i class="bi bi-stars"></i> Alpha 完整排名
                        </a>
                        <a href="{% url 'equity:valuation_repair' %}" class="dropdown-item">
                            <i class="bi bi-arrow-up-circle"></i> 估值修复跟踪
                        </a>
                        <a href="{% url 'fund:dashboard' %}" class="dropdown-item">
                            <i class="bi bi-pie-chart"></i> 基金总览
                        </a>
                        <a href="{% url 'asset-screen' %}" class="dropdown-item">
                            <i class="bi bi-funnel"></i> 资产筛选
                        </a>
                    </div>
                </div>

                <!-- 智能模块：下拉菜单 -->
                {% if user.is_staff %}
                <div class="dropdown">
                    <button type="button" class="top-nav-item dropdown-trigger" aria-haspopup="true" aria-expanded="false">智能模块</button>
                    <div class="dropdown-menu">
                        <div class="dropdown-section-title">因子分析</div>
                        <a href="{% url 'factor:manage' %}" class="dropdown-item">
                            <i class="bi bi-calculator"></i> 因子管理
                        </a>
                        <a href="{% url 'factor:portfolios' %}" class="dropdown-item">
                            <i class="bi bi-collection"></i> 组合配置
                        </a>
                        <a href="{% url 'factor:calculate' %}" class="dropdown-item">
                            <i class="bi bi-sort-numeric-up"></i> 因子计算
                        </a>
                        <div class="dropdown-divider"></div>
                        <div class="dropdown-section-title">轮动策略</div>
                        <a href="{% url 'rotation:assets' %}" class="dropdown-item">
                            <i class="bi bi-grid-3x3-gap"></i> 资产列表
                        </a>
                        <a href="{% url 'rotation:configs' %}" class="dropdown-item">
                            <i class="bi bi-gear"></i> 轮动配置
                        </a>
                        <a href="{% url 'rotation:signals' %}" class="dropdown-item">
                            <i class="bi bi-arrow-left-right"></i> 轮动信号
                        </a>
                        <div class="dropdown-divider"></div>
                        <div class="dropdown-section-title">对冲策略</div>
                        <a href="{% url 'hedge:pairs' %}" class="dropdown-item">
                            <i class="bi bi-link-45deg"></i> 对冲对管理
                        </a>
                        <a href="{% url 'hedge:snapshots' %}" class="dropdown-item">
                            <i class="bi bi-box-seam"></i> 组合持仓
                        </a>
                        <a href="{% url 'hedge:alerts' %}" class="dropdown-item">
                            <i class="bi bi-bell"></i> 告警中心
                        </a>
                    </div>
                </div>
                {% endif %}

                {% endif %}

                <!-- 平台：下拉菜单 -->
                <div class="dropdown">
                    <button type="button" class="top-nav-item dropdown-trigger" aria-haspopup="true" aria-expanded="false">平台</button>
                    <div class="dropdown-menu">
                        {% if user.is_staff %}
                        <div class="dropdown-section-title">设置与配置</div>
                        <a href="{% url 'settings-center' %}" class="dropdown-item">设置中心</a>
                        {% if user.is_superuser %}
                        <a href="{% url 'account:system_settings' %}" class="dropdown-item">系统设置</a>
                        {% endif %}
                        <div class="dropdown-divider"></div>
                        <div class="dropdown-section-title">数据源</div>
                        <a href="{% url 'data_center:dc-providers-page' %}" class="dropdown-item">财经数据源配置</a>
                        <a href="{% url 'data_center:dc-monitor-page' %}" class="dropdown-item"><i class="bi bi-database-check"></i> 统一数据源运行状态</a>
                        <a href="{% url 'macro:data_controller' %}" class="dropdown-item">数据管理器</a>
                        <div class="dropdown-divider"></div>
                        <div class="dropdown-section-title">AI 与自动化</div>
                        <a href="{% url 'terminal' %}" class="dropdown-item" target="_blank">
                            <i class="bi bi-terminal"></i> AI Terminal
                        </a>
                        <a href="{% url 'account:mcp_guide' %}" class="dropdown-item">MCP 接入说明</a>
                        <a href="{% url 'settings-mcp-tools' %}" class="dropdown-item">MCP 工具</a>
                        <a href="{% url 'ai_provider:manage' %}" class="dropdown-item">AI接口管理</a>
                        <a href="{% url 'prompt:prompt-manage' %}" class="dropdown-item">Prompt模板管理</a>
                        <div class="dropdown-divider"></div>
                        <div class="dropdown-section-title">运行校验</div>
                        <a href="{% url 'audit:indicator_performance' %}" class="dropdown-item">指标表现校验</a>
                        <a href="{% url 'audit:threshold_validation' %}" class="dropdown-item">阈值验证</a>
                        {% endif %}
                    </div>
                </div>

                <!-- 帮助：下拉菜单 -->
                <div class="dropdown">
                    <button type="button" class="top-nav-item dropdown-trigger" aria-haspopup="true" aria-expanded="false">帮助</button>
                    <div class="dropdown-menu">
                        <div class="dropdown-section-title">文档与接口</div>
                        <a href="{% url 'docs' %}" class="dropdown-item">文档中心</a>
                        <a href="/api/docs/" class="dropdown-item">API 文档</a>
                    </div>
                </div>

                {% if user.is_superuser %}
                <div class="dropdown">
                    <button type="button" class="top-nav-item dropdown-trigger" aria-haspopup="true" aria-expanded="false">运维</button>
                    <div class="dropdown-menu">
                        <div class="dropdown-section-title">管理入口</div>
                        <a href="{% url 'admin-console' %}" class="dropdown-item">管理控制台</a>
                        <div class="dropdown-divider"></div>
                        <div class="dropdown-section-title">Alpha 与 Qlib</div>
                        <a href="{% url 'alpha:ops-inference' %}" class="dropdown-item">Alpha 推理管理</a>
                        <a href="{% url 'alpha:ops-qlib-data' %}" class="dropdown-item">Qlib 基础数据管理</a>
                        <div class="dropdown-divider"></div>
                        <div class="dropdown-section-title">管理员与访问控制</div>
                        <a href="{% url 'account:user_management' %}" class="dropdown-item">用户管理</a>
                        <a href="{% url 'account:token_management' %}" class="dropdown-item">Token管理</a>
                        <div class="dropdown-divider"></div>
                        <div class="dropdown-section-title">日志与后台</div>
                        <a href="{% url 'task_monitor_pages:scheduler_console' %}" class="dropdown-item">计划任务中心</a>
                        <a href="{% url 'ai_provider:logs' %}" class="dropdown-item">AI调用日志</a>
                        <a href="{% url 'admin-server-logs' %}" class="dropdown-item">服务器日志</a>
                        <a href="{% url 'admin-docs-manage' %}" class="dropdown-item">文档管理</a>
                        <div class="dropdown-divider"></div>
                        <a href="/admin/" class="dropdown-item">Django Admin</a>
                    </div>
                </div>
                {% endif %}
            </nav>

            <div class="header-actions">
                {% if user.is_staff %}
                <a href="{% url 'terminal' %}" target="_blank" class="terminal-entry-btn" title="AI Terminal">
                    <span class="terminal-entry-icon">>&lowbar;Cli</span>
                </a>
                {% endif %}
                {% if user.is_authenticated %}
                <div class="dropdown">
                    <button type="button" class="top-nav-item dropdown-trigger" aria-haspopup="true" aria-expanded="false">
                        {{ user.account_profile.display_name|default:user.username }}
                    </button>
                    <div class="dropdown-menu">
                        <a href="{% url 'account:profile' %}" class="dropdown-item">我的账户</a>
                        <a href="{% url 'account:mcp_guide' %}" class="dropdown-item">MCP 接入说明</a>
                        <a href="{% url 'settings-center' %}" class="dropdown-item">设置中心</a>
                        {% if user.is_staff %}
                        <a href="{% url 'alpha:ops-inference' %}" class="dropdown-item">Alpha 推理管理</a>
                        <a href="{% url 'alpha:ops-qlib-data' %}" class="dropdown-item">Qlib 基础数据管理</a>
                        {% endif %}
                        <div class="dropdown-divider"></div>
                        <a href="{% url 'account:logout' %}" class="dropdown-item">登出</a>
                    </div>
                </div>
                {% else %}
                <a href="{% url 'account:login' %}" class="btn btn-primary">登录</a>
                <a href="{% url 'account:register' %}" class="btn btn-secondary">注册</a>
                {% endif %}
            </div>
        </div>
    </header>

    <!-- 全局 Toast 通知 -->
    <div id="toast-container" class="toast-container"></div>

    <!-- 信息中心（右下角浮动） -->
    {% load alert_tags %}
    {% alert_banner global_alerts %}

    <!-- 消息提示 -->
    {% if messages %}
    <div class="messages-container">
        {% for message in messages %}
        <div class="alert alert-{{ message.tags }}">
            {{ message }}
        </div>
        {% endfor %}
    </div>
    {% endif %}

    <!-- 主内容区域 -->
    <main class="main-content-full" id="mainContent">
        {% block content %}{% endblock %}
    </main>



    <!-- 页脚 -->
    <footer class="footer-full">
        <div class="footer-content">
            <p>&copy; 2026 AgomTradePro. 作者：<a href="https://github.com/guiyinan" target="_blank" rel="noopener">Agomliou</a></p>
            <p class="footer-disclaimer"><strong>系统中的任何信息均系用于研究，不构成任何投资建议。市场有风险，投资需谨慎。</strong></p>
        </div>
    </footer>

    <!-- 全局 JavaScript -->
    <script>
    // Toast 通知系统
    (function() {
        const container = document.getElementById('toast-container');

        function showToast(message, type = 'info', duration = 3000) {
            const toast = document.createElement('div');
            toast.className = `toast toast-${type}`;

            // 图标映射
            const icons = {
                success: '✓',
                error: '✕',
                warning: '⚠️',
                info: 'ℹ️'
            };

            const icon = icons[type] || icons.info;
            toast.innerHTML = `<span class="toast-icon">${icon}</span><span class="toast-message">${message}</span>`;

            container.appendChild(toast);

            // 触发动画
            setTimeout(() => toast.classList.add('toast-show'), 10);

            // 自动移除
            setTimeout(() => {
                toast.classList.remove('toast-show');
                setTimeout(() => toast.remove(), 300);
            }, duration);
        }

        // 全局可用
        window.showToast = showToast;

        // 兼容旧代码的 alert 替换
        window.alert = function(message) {
            // 判断消息类型
            let type = 'info';
            if (typeof message === 'string') {
                if (message.startsWith('✓') || message.includes('成功')) {
                    type = 'success';
                } else if (message.startsWith('✗') || message.includes('失败') || message.includes('错误')) {
                    type = 'error';
                } else if (message.startsWith('⚠️') || message.includes('警告')) {
                    type = 'warning';
                }
            }
            showToast(message, type);
        };

        // Async confirm/prompt helpers for consistent UX across pages.
        window.uiConfirm = async function(message, options = {}) {
            if (typeof Swal === 'undefined') {
                return window.confirm(message);
            }
            const result = await Swal.fire({
                title: options.title || '请确认',
                text: message || '',
                icon: options.icon || 'question',
                showCancelButton: true,
                confirmButtonText: options.confirmText || '确认',
                cancelButtonText: options.cancelText || '取消',
                reverseButtons: true,
            });
            return !!result.isConfirmed;
        };

        window.uiPrompt = async function(label, defaultValue = '', options = {}) {
            if (typeof Swal === 'undefined') {
                const value = window.prompt(label || '', defaultValue || '');
                return value === null ? null : String(value);
            }
            const result = await Swal.fire({
                title: options.title || '请输入',
                input: 'text',
                inputLabel: label || '',
                inputValue: defaultValue || '',
                inputPlaceholder: options.placeholder || '',
                showCancelButton: true,
                confirmButtonText: options.confirmText || '确认',
                cancelButtonText: options.cancelText || '取消',
                reverseButtons: true,
                inputValidator: (value) => {
                    if (options.required && !String(value || '').trim()) {
                        return options.requiredMessage || '该项不能为空';
                    }
                    return undefined;
                }
            });
            return result.isConfirmed ? String(result.value ?? '') : null;
        };
    })();

    // CSRF Token 获取
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 全局 CSRF Token
    window.csrfToken = getCookie('csrftoken');

    // ===== 同源 Fetch 默认行为 =====
    (function() {
        if (typeof window.fetch !== 'function') {
            return;
        }

        const nativeFetch = window.fetch.bind(window);
        const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);

        function isSameOriginRequest(resource) {
            try {
                const rawUrl = resource instanceof Request ? resource.url : String(resource);
                const requestUrl = new URL(rawUrl, window.location.href);
                return requestUrl.origin === window.location.origin;
            } catch (error) {
                return false;
            }
        }

        function buildFetchInit(resource, init = {}) {
            if (!isSameOriginRequest(resource)) {
                return init;
            }

            const finalInit = { ...init };
            if (typeof finalInit.credentials === 'undefined') {
                finalInit.credentials = 'same-origin';
            }

            const method = (
                finalInit.method ||
                (resource instanceof Request ? resource.method : 'GET') ||
                'GET'
            ).toUpperCase();

            if (!SAFE_METHODS.has(method)) {
                const headers = new Headers(resource instanceof Request ? resource.headers : undefined);
                const overrideHeaders = new Headers(finalInit.headers || {});
                overrideHeaders.forEach((value, key) => headers.set(key, value));

                if (!headers.has('X-CSRFToken') && window.csrfToken) {
                    headers.set('X-CSRFToken', window.csrfToken);
                }
                finalInit.headers = headers;
            }

            return finalInit;
        }

        async function extractResponseErrorMessage(response) {
            const clone = response.clone();
            const contentType = clone.headers.get('content-type') || '';

            function flattenPayloadErrors(payload) {
                if (!payload || typeof payload !== 'object') {
                    return '';
                }

                if (typeof payload.errors === 'string') {
                    return payload.errors;
                }

                if (payload.errors && typeof payload.errors === 'object') {
                    const collected = Object.entries(payload.errors).flatMap(([field, value]) => {
                        if (Array.isArray(value)) {
                            return value.map((item) => `${field}: ${item}`);
                        }
                        if (value && typeof value === 'object') {
                            return Object.values(value).flat().map((item) => `${field}: ${item}`);
                        }
                        return [`${field}: ${value}`];
                    }).filter(Boolean);

                    return collected.join('; ');
                }

                return '';
            }

            try {
                if (contentType.includes('application/json')) {
                    const payload = await clone.json();
                    return (
                        payload?.error ||
                        payload?.detail ||
                        flattenPayloadErrors(payload) ||
                        payload?.message ||
                        `HTTP ${response.status}`
                    );
                }

                if (contentType.includes('text/html')) {
                    return `HTTP ${response.status} (HTML response)`;
                }

                const text = (await clone.text()).trim();
                return text || `HTTP ${response.status}`;
            } catch (error) {
                return `HTTP ${response.status}`;
            }
        }

        window.fetch = function(resource, init) {
            return nativeFetch(resource, buildFetchInit(resource, init));
        };

        window.assertOkResponse = async function(response) {
            if (response.ok) {
                return response;
            }
            throw new Error(await extractResponseErrorMessage(response));
        };

        window.fetchJsonOrThrow = async function(resource, init = {}) {
            const response = await window.fetch(resource, init);
            await window.assertOkResponse(response);

            const contentType = response.headers.get('content-type') || '';
            if (!contentType.includes('application/json')) {
                throw new Error(`Expected JSON but received ${contentType || 'unknown content type'}`);
            }

            return response.json();
        };
    })();

    // ===== HTMX 配置 =====
    document.body.addEventListener('htmx:configRequest', function(evt) {
        // 为所有 HTMX 请求添加 CSRF Token
        evt.detail.headers['X-CSRFToken'] = window.csrfToken;
    });

    document.body.addEventListener('htmx:beforeRequest', function(evt) {
        // 请求前显示加载指示器
        console.log('HTMX 请求:', evt.detail.pathInfo.requestPath);
    });

    document.body.addEventListener('htmx:afterRequest', function(evt) {
        // 请求完成后隐藏加载指示器
        if (evt.detail.xhr.status >= 400) {
            // 处理错误
            const errorMsg = evt.detail.xhr.responseText || '请求失败';
            showToast(errorMsg, 'error');
        }
    });

    document.body.addEventListener('htmx:afterSwap', function(evt) {
        // DOM 更新后重新初始化组件
        console.log('HTMX 内容已更新:', evt.detail.target.id);

        // 重新初始化日期选择器
        if (typeof flatpickr !== 'undefined') {
            evt.detail.target.querySelectorAll('input[data-datepicker]').forEach(function(input) {
                flatpickr(input, {
                    locale: 'zh',
                    dateFormat: 'Y-m-d'
                });
            });
        }
    });

    // HTMX 错误处理
    document.body.addEventListener('htmx:responseError', function(evt) {
        showToast('服务器错误: ' + evt.detail.xhr.status, 'error');
    });

    // HTMX 超时处理
    document.body.addEventListener('htmx:sendError', function(evt) {
        showToast('网络错误，请检查连接', 'error');
    });

    // 顶部导航交互：支持点击、键盘与当前页高亮
    (function() {
        const dropdowns = Array.from(document.querySelectorAll('.header .dropdown'));
        const supportsHover = window.matchMedia('(hover: hover) and (pointer: fine)').matches;

        function closeAll(except) {
            dropdowns.forEach((dropdown) => {
                if (dropdown !== except) {
                    dropdown.classList.remove('open');
                    const trigger = dropdown.querySelector('.dropdown-trigger');
                    if (trigger) {
                        trigger.setAttribute('aria-expanded', 'false');
                    }
                }
            });
        }

        dropdowns.forEach((dropdown) => {
            const trigger = dropdown.querySelector('.dropdown-trigger');
            if (!trigger) return;

            trigger.addEventListener('click', function(e) {
                e.preventDefault();
                const isOpen = dropdown.classList.contains('open');
                closeAll(dropdown);
                dropdown.classList.toggle('open', !isOpen);
                trigger.setAttribute('aria-expanded', String(!isOpen));
            });

            trigger.addEventListener('keydown', function(e) {
                if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    closeAll(dropdown);
                    dropdown.classList.add('open');
                    trigger.setAttribute('aria-expanded', 'true');
                    const firstItem = dropdown.querySelector('.dropdown-item');
                    if (firstItem) firstItem.focus();
                }
            });

            if (supportsHover) {
                dropdown.addEventListener('mouseleave', function() {
                    dropdown.classList.remove('open');
                    trigger.setAttribute('aria-expanded', 'false');
                });
            }
        });

        document.addEventListener('click', function(e) {
            if (!e.target.closest('.header .dropdown')) {
                closeAll();
            }
        });

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeAll();
            }
        });

        const currentPath = window.location.pathname;
        document.querySelectorAll('.header .dropdown').forEach((dropdown) => {
            const items = Array.from(dropdown.querySelectorAll('.dropdown-item[href]'));
            const hasMatch = items.some((item) => {
                try {
                    const path = new URL(item.href, window.location.origin).pathname;
                    if (path === '/') {
                        return currentPath === '/';
                    }
                    return currentPath === path || currentPath.startsWith(path.endsWith('/') ? path : path + '/');
                } catch {
                    return false;
                }
            });
            if (hasMatch) {
                const trigger = dropdown.querySelector('.dropdown-trigger');
                if (trigger) trigger.classList.add('active');
            }
        });
    })();

    // 前端工具函数库
    </script>
    <script src="{% static 'js/utils.js' %}"></script>
    <script src="{% static 'js/htmx-config.js' %}"></script>

    {% block extra_js %}{% endblock %}

    <!-- Floating Widget JS -->
    <script src="{% static 'js/components/floating-widget.js' %}"></script>
</body>
</html>
