{% extends "_base.html" %}

{% block title %}MES 報表入口{% endblock %}

{% block head_extra %}
    <script>if (window.self !== window.top) { window.top.location.href = window.self.location.href; }</script>
    {% set portal_css = frontend_asset('portal.css') %}
    {% if portal_css %}
    <link rel="stylesheet" href="{{ portal_css }}">
    {% endif %}
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft JhengHei', Arial, sans-serif;
            background: #f5f7fa;
            color: #222;
        }

        .shell {
            max-width: 1600px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 24px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
            margin-bottom: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header-left h1 {
            font-size: 26px;
            margin-bottom: 6px;
        }

        .header-left p {
            font-size: 14px;
            opacity: 0.9;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 12px;
            position: relative;
        }

        .admin-status {
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .admin-status a {
            color: white;
            text-decoration: none;
            padding: 6px 12px;
            border-radius: 6px;
            background: rgba(255, 255, 255, 0.15);
            transition: background 0.2s ease;
        }

        .admin-status a:hover {
            background: rgba(255, 255, 255, 0.25);
        }

        .admin-name {
            opacity: 0.9;
        }

        .health-status {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 6px 12px;
            background: rgba(255, 255, 255, 0.15);
            border-radius: 6px;
            font-size: 12px;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .health-status:hover {
            background: rgba(255, 255, 255, 0.25);
        }

        .health-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #9ca3af;
            transition: background 0.3s ease;
        }

        .health-dot.healthy {
            background: #22c55e;
            box-shadow: 0 0 6px rgba(34, 197, 94, 0.6);
        }

        .health-dot.degraded {
            background: #f59e0b;
            box-shadow: 0 0 6px rgba(245, 158, 11, 0.6);
        }

        .health-dot.unhealthy {
            background: #ef4444;
            box-shadow: 0 0 6px rgba(239, 68, 68, 0.6);
        }

        .health-dot.loading {
            background: #9ca3af;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.4; }
        }

        .health-label {
            opacity: 0.9;
        }

        .health-popup {
            position: absolute;
            top: 100%;
            right: 0;
            margin-top: 8px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            padding: 16px;
            min-width: 280px;
            z-index: 1000;
            display: none;
            color: #333;
        }

        .health-popup.show {
            display: block;
        }

        .health-popup h4 {
            margin: 0 0 12px 0;
            font-size: 14px;
            color: #667eea;
            border-bottom: 1px solid #e5e7eb;
            padding-bottom: 8px;
        }

        .health-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            font-size: 13px;
        }

        .health-item:not(:last-child) {
            border-bottom: 1px solid #f3f4f6;
        }

        .health-item-label {
            color: #6b7280;
        }

        .health-item-value {
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .health-item-value.ok {
            color: #22c55e;
        }

        .health-item-value.error {
            color: #ef4444;
        }

        .health-item-value.disabled {
            color: #9ca3af;
        }

        .health-cache-info {
            margin-top: 12px;
            padding-top: 12px;
            border-top: 1px solid #e5e7eb;
            font-size: 12px;
            color: #6b7280;
        }

        .health-cache-info div {
            margin-bottom: 4px;
        }

        .main-layout {
            display: flex;
            gap: 12px;
            min-height: calc(100vh - 140px);
        }

        .sidebar {
            width: 200px;
            min-width: 200px;
            background: white;
            border-radius: 10px;
            border: 1px solid #e3e8f2;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
            overflow-y: auto;
            align-self: flex-start;
            position: sticky;
            top: 20px;
        }

        .panel {
            flex: 1;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            min-width: 0;
            padding: 24px;
        }

        .panel h2 {
            font-size: 20px;
            margin-bottom: 10px;
            color: #1f2937;
        }

        .panel p {
            font-size: 14px;
            color: #64748b;
            line-height: 1.6;
            margin-bottom: 8px;
        }

        .route-status {
            border-radius: 8px;
            border: 1px solid #e2e8f0;
            background: #f8fafc;
            padding: 10px 12px;
            margin-top: 12px;
            color: #475569;
        }

        .route-status.loading {
            border-color: #c7d2fe;
            background: #eef2ff;
            color: #4338ca;
            font-weight: 600;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="shell" data-portal-spa-enabled="{{ 'true' if portal_spa_enabled else 'false' }}">
        <div class="header">
            <div class="header-left">
                <h1>MES 報表入口</h1>
                <p>統一入口：WIP 即時看板、設備即時概況與數據表查詢工具</p>
            </div>
            <div class="header-right">
                <div class="health-status" id="healthStatus" onclick="toggleHealthPopup()">
                    <span class="health-dot loading" id="healthDot"></span>
                    <span class="health-label" id="healthLabel">檢查中...</span>
                </div>
                <div class="health-popup" id="healthPopup">
                    <h4>系統連線狀態</h4>
                    <div class="health-item">
                        <span class="health-item-label">資料庫 (Oracle)</span>
                        <span class="health-item-value" id="dbStatus">--</span>
                    </div>
                    <div class="health-item">
                        <span class="health-item-label">快取 (Redis)</span>
                        <span class="health-item-value" id="redisStatus">--</span>
                    </div>
                    <div class="health-cache-info" id="cacheInfo">
                        <h5 style="margin: 8px 0 4px 0; font-size: 12px; color: #667eea;">WIP 快取</h5>
                        <div>狀態：<span id="cacheEnabled">--</span></div>
                        <div>資料更新時間：<span id="cacheSysDate">--</span></div>
                        <div>最後同步：<span id="cacheUpdatedAt">--</span></div>
                    </div>
                    <div class="health-cache-info" id="resourceCacheInfo">
                        <h5 style="margin: 8px 0 4px 0; font-size: 12px; color: #667eea;">設備主檔快取</h5>
                        <div>狀態：<span id="resourceCacheEnabled">--</span></div>
                        <div>資料筆數：<span id="resourceCacheCount">--</span></div>
                        <div>最後同步：<span id="resourceCacheUpdatedAt">--</span></div>
                    </div>
                    <div class="health-cache-info" id="routeCacheInfo">
                        <h5 style="margin: 8px 0 4px 0; font-size: 12px; color: #667eea;">路由快取 (L1/L2)</h5>
                        <div>模式：<span id="routeCacheMode">--</span></div>
                        <div>L1/L2 命中：<span id="routeCacheHitRate">--</span></div>
                        <div>降級模式：<span id="routeCacheDegraded">--</span></div>
                    </div>
                </div>
                <div class="admin-status">
                    {% if is_admin %}
                        <span class="admin-name">{{ admin_user.displayName }}</span>
                        <a href="{{ url_for('auth.logout') }}">登出</a>
                    {% else %}
                        <a href="{{ url_for('auth.login') }}">管理員登入</a>
                    {% endif %}
                </div>
            </div>
        </div>

        <div class="main-layout">
            <nav class="sidebar">
                {% for drawer in drawers | default([]) %}
                    {% if not drawer.admin_only or is_admin %}
                        {% set nav_ns = namespace(has_visible_pages=false) %}
                        {% for page in drawer.pages %}
                            {% if can_view_page(page.route) %}
                                {% set nav_ns.has_visible_pages = true %}
                            {% endif %}
                        {% endfor %}
                        {% if nav_ns.has_visible_pages %}
                            <div class="sidebar-group-title">{{ drawer.name }}</div>
                            {% for page in drawer.pages %}
                                {% if can_view_page(page.route) %}
                                <a
                                    class="sidebar-item{% if request.path == page.route %} active{% endif %}"
                                    href="{{ page.route }}"
                                    data-route="{{ page.route }}"
                                    data-page-name="{{ page.name }}"
                                >{{ page.name }}</a>
                                {% endif %}
                            {% endfor %}
                        {% endif %}
                    {% endif %}
                {% endfor %}
                {% if not is_admin %}
                <a class="sidebar-item" href="{{ url_for('auth.login') }}">管理員登入</a>
                {% endif %}
            </nav>

            <section class="panel" aria-live="polite">
                <h2>路由導覽模式</h2>
                <p>抽屜已與 iframe 載入機制解耦，點選左側項目將直接進入既有路由頁面。</p>
                <p>目前仍保留抽屜分組、排序與 admin 權限控制規則。</p>
                <p id="routeStatus" class="route-status">請從左側抽屜選擇頁面。</p>
            </section>
        </div>
    </div>
{% endblock %}

{% block scripts %}
    {% set portal_js = frontend_asset('portal.js') %}
    {% if portal_js %}
    <script type="module" src="{{ portal_js }}"></script>
    {% else %}
    <script>
        (function portalFallback() {
            const routeStatus = document.getElementById('routeStatus');
            const sidebarItems = document.querySelectorAll('.sidebar-item[data-route]');
            const healthPopup = document.getElementById('healthPopup');

            sidebarItems.forEach((item) => {
                item.addEventListener('click', () => {
                    if (!routeStatus) return;
                    routeStatus.classList.add('loading');
                    routeStatus.textContent = `正在前往 ${item.dataset.pageName || item.dataset.route}...`;
                });
            });

            window.toggleHealthPopup = function toggleHealthPopup() {
                if (!healthPopup) return;
                healthPopup.classList.toggle('show');
            };

            document.addEventListener('click', (e) => {
                if (!e.target.closest('#healthStatus') && !e.target.closest('#healthPopup') && healthPopup) {
                    healthPopup.classList.remove('show');
                }
            });
        })();
    </script>
    {% endif %}
{% endblock %}
