<!DOCTYPE html>
<html lang="{{ current_locale or 'en' }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="theme-color" content="#3b82f6" id="meta-theme-color">
    <meta id="user-theme-pref" data-user-theme="{{ current_user.theme_preference if current_user.is_authenticated else '' }}">
    <title>{% block title %}{{ app_name }}{% endblock %}</title>
    
    <!-- Favicon -->
    {% if settings and settings.has_logo() %}
    <link rel="icon" type="image/x-icon" href="{{ settings.get_logo_url() }}">
    {% else %}
    <link rel="icon" type="image/svg+xml" href="{{ url_for('static', filename='images/drytrix-logo.svg') }}">
    {% endif %}
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- jQuery (required for DataTables) -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <!-- DataTables CSS and JS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css">
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.js"></script>
    <!-- Custom CSS (cache-busted with app_version) -->
    <link rel="stylesheet" href="{{ url_for('static', filename='base.css') }}?v={{ app_version }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='mobile.css') }}?v={{ app_version }}">
    
    {% block extra_css %}{% endblock %}
    {% block head_extra %}{% endblock %}
    <script>
        (function() {
            try {
                const storageKey = 'tt-theme';
                const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
                const saved = localStorage.getItem(storageKey);
                const userMeta = document.getElementById('user-theme-pref');
                const serverPrefRaw = userMeta ? (userMeta.getAttribute('data-user-theme') || '').trim().toLowerCase() : '';
                const serverPref = (serverPrefRaw === 'light' || serverPrefRaw === 'dark') ? serverPrefRaw : null;
                const theme = serverPref || saved || (prefersDark ? 'dark' : 'light');
                const root = document.documentElement;
                root.setAttribute('data-theme', theme);
                if (serverPref) {
                    root.setAttribute('data-theme-locked', 'user');
                } else if (saved) {
                    root.setAttribute('data-theme-locked', 'local');
                }
                const meta = document.getElementById('meta-theme-color');
                if (meta) meta.setAttribute('content', theme === 'dark' ? '#0b1220' : '#3b82f6');
            } catch (e) {}
        })();
    </script>
</head>
<body>
    <div id="toast-container" class="toast-container position-fixed top-0 end-0 p-3"></div>
    <!-- Enhanced Navigation -->
    <nav class="navbar navbar-expand-lg navbar-light sticky-top">
        <div class="container">
            <a class="navbar-brand" href="{{ url_for('main.dashboard') }}">
                {% if settings and settings.has_logo() %}
        <img src="{{ settings.get_logo_url() }}" alt="Company Logo" width="36" height="36">
        {% else %}
        <img src="{{ url_for('static', filename='images/drytrix-logo.svg') }}" alt="DryTrix Logo" width="36" height="36">
        {% endif %}
                <span class="text-dark fw-bold">{{ _('Time Tracker') }}</span>
            </a>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                {% if current_user.is_authenticated %}
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint == 'main.dashboard' %}active{% endif %}" {% if request.endpoint == 'main.dashboard' %}aria-current="page"{% endif %} href="{{ url_for('main.dashboard') }}">
                            <i class="fas fa-tachometer-alt"></i>{{ _('Dashboard') }}
                        </a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle {% if request.endpoint and ('projects.' in request.endpoint or 'clients.' in request.endpoint or 'tasks.' in request.endpoint or 'timer.' in request.endpoint) %}active{% endif %}"
                           href="#" id="workDropdown" role="button" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
                            <i class="fas fa-briefcase"></i>{{ _('Work') }}
                        </a>
                        <ul class="dropdown-menu" aria-labelledby="workDropdown">
                            <li><a class="dropdown-item" href="{{ url_for('projects.list_projects') }}"><i class="fas fa-project-diagram me-2"></i>{{ _('Projects') }}</a></li>
                            <li><a class="dropdown-item" href="{{ url_for('clients.list_clients') }}"><i class="fas fa-building me-2"></i>{{ _('Clients') }}</a></li>
                            <li><a class="dropdown-item" href="{{ url_for('tasks.list_tasks') }}"><i class="fas fa-tasks me-2"></i>{{ _('Tasks') }}</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="{{ url_for('timer.manual_entry') }}"><i class="fas fa-plus me-2"></i>{{ _('Log Time') }}</a></li>
                            <li><a class="dropdown-item" href="{{ url_for('timer.bulk_entry') }}"><i class="fas fa-calendar-plus me-2"></i>{{ _('Bulk Time Entry') }}</a></li>
                        </ul>
                    </li>

                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle {% if request.endpoint and ('reports.' in request.endpoint or 'invoices.' in request.endpoint or 'analytics.' in request.endpoint) %}active{% endif %}"
                           href="#" id="insightsDropdown" role="button" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
                            <i class="fas fa-chart-line"></i>{{ _('Insights') }}
                        </a>
                        <ul class="dropdown-menu" aria-labelledby="insightsDropdown">
                            <li><a class="dropdown-item" href="{{ url_for('reports.reports') }}"><i class="fas fa-chart-bar me-2"></i>{{ _('Reports') }}</a></li>
                            <li><a class="dropdown-item" href="{{ url_for('invoices.list_invoices') }}"><i class="fas fa-file-invoice-dollar me-2"></i>{{ _('Invoices') }}</a></li>
                            <li><a class="dropdown-item" href="{{ url_for('analytics.analytics_dashboard') }}"><i class="fas fa-chart-line me-2"></i>{{ _('Analytics') }}</a></li>
                        </ul>
                    </li>
                    {% if current_user.is_admin %}
                    <li class="nav-item">
                        <a class="nav-link {% if request.endpoint and 'admin.' in request.endpoint %}active{% endif %}" {% if request.endpoint and 'admin.' in request.endpoint %}aria-current="page"{% endif %} href="{{ url_for('admin.admin_dashboard') }}">
                            <i class="fas fa-cog"></i>{{ _('Admin') }}
                        </a>
                    </li>
                    {% endif %}
                </ul>
                
                <ul class="navbar-nav ms-auto">
                    {% if current_user.is_authenticated %}
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle d-flex align-items-center" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" data-bs-display="static" aria-expanded="false">
                            <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 36px; height: 36px;">
                                <i class="fas fa-user text-primary"></i>
                            </div>
                            <span>{{ current_user.display_name }}</span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="{{ url_for('auth.profile') }}">
                                <i class="fas fa-user-circle me-2"></i>{{ _('Profile') }}
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="{{ url_for('auth.logout') }}">
                                <i class="fas fa-sign-out-alt me-2"></i>{{ _('Logout') }}
                            </a></li>
                        </ul>
                    </li>
                    {% endif %}
                </ul>
                {% endif %}
            </div>
        </div>
    </nav>

    <!-- Enhanced Main Content -->
    <main class="container mt-4">
        <!-- Enhanced Flash Messages -->
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="alert alert-{{ 'danger' if category == 'error' else category }} alert-dismissible fade show fade-in" role="alert">
                        {{ message }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                {% endfor %}
            {% endif %}
        {% endwith %}

        <!-- Enhanced Page Content -->
        {% block content %}{% endblock %}
    </main>

    <!-- Mobile Bottom Tab Bar -->
    {% if current_user.is_authenticated %}
    <div class="mobile-tabbar d-lg-none">
        <a href="{{ url_for('main.dashboard') }}" class="tab-item {% if request.endpoint == 'main.dashboard' %}active{% endif %}" aria-label="{{ _('Dashboard') }}">
            <i class="fas fa-tachometer-alt tab-icon"></i>
            <span>{{ _('Home') }}</span>
        </a>
        <a href="{{ url_for('timer.manual_entry') }}" class="tab-item {% if request.endpoint and 'timer.' in request.endpoint %}active{% endif %}" aria-label="{{ _('Log Time') }}">
            <i class="fas fa-plus tab-icon"></i>
            <span>{{ _('Log') }}</span>
        </a>
        <a href="{{ url_for('tasks.list_tasks') }}" class="tab-item {% if request.endpoint and 'tasks.' in request.endpoint %}active{% endif %}" aria-label="{{ _('Tasks') }}">
            <i class="fas fa-tasks tab-icon"></i>
            <span>{{ _('Tasks') }}</span>
        </a>
        <a href="{{ url_for('reports.reports') }}" class="tab-item {% if request.endpoint and 'reports.' in request.endpoint %}active{% endif %}" aria-label="{{ _('Reports') }}">
            <i class="fas fa-chart-bar tab-icon"></i>
            <span>{{ _('Reports') }}</span>
        </a>
    </div>
    {% endif %}

    <!-- Enhanced Footer -->
    <footer class="footer mt-auto">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <p class="mb-0 text-muted">
                        &copy; 2025 <strong>DryTrix</strong>. {{ _('All rights reserved.') }}
                    </p>
                </div>
                <div class="col-md-6 text-md-end">
                    <div class="d-flex justify-content-md-end gap-3 align-items-center">
                        <small class="text-muted">{{ app_version }}</small>
                        <small><a href="{{ url_for('main.about') }}" class="text-decoration-none">{{ _('About') }}</a></small>
                        <small><a href="{{ url_for('main.help') }}" class="text-decoration-none">{{ _('Help') }}</a></small>
                        <small>
                            <a href="https://buymeacoffee.com/DryTrix" target="_blank" rel="noopener" class="text-decoration-none">
                                <i class="fas fa-mug-hot me-1"></i> {{ _('Buy me a coffee') }}
                            </a>
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </footer>

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

    <script type="application/json" id="i18n-json">
        {
            "close": {{ _('Close')|tojson }},
            "timer_started_for": {{ _('Timer started for')|tojson }},
            "timer_stopped_duration": {{ _('Timer stopped. Duration:')|tojson }},
            "switch_to_light_mode": {{ _('Switch to light mode')|tojson }},
            "switch_to_dark_mode": {{ _('Switch to dark mode')|tojson }},
            "light_mode": {{ _('Light mode')|tojson }},
            "dark_mode": {{ _('Dark mode')|tojson }}
        }
    </script>
    <script>
        // Parse i18n JSON into a global variable
        var i18n = (function(){
            try {
                var el = document.getElementById('i18n-json');
                return el ? JSON.parse(el.textContent) : {};
            } catch (e) { return {}; }
        })();

        // Global helpers available on all pages
        function formatDuration(seconds) {
            const total = Number(seconds) || 0;
            const hours = Math.floor(total / 3600);
            const minutes = Math.floor((total % 3600) / 60);
            const secs = total % 60;
            return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
        }

        function showToast(message, type = 'info') {
            const container = document.getElementById('toast-container');
            if (!container) {
                // Fallback: alert when toast container not present
                try { console.warn('Toast container missing:', message); } catch(e) {}
                return;
            }
            const toast = document.createElement('div');
            toast.className = `toast align-items-center text-white bg-${type} border-0 fade`;
            toast.setAttribute('role', 'alert');
            toast.setAttribute('aria-live', 'assertive');
            toast.setAttribute('aria-atomic', 'true');
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">${message}</div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="${i18n.close}"></button>
                </div>`;
            container.appendChild(toast);
            try {
                const bsToast = new bootstrap.Toast(toast, { delay: 3000 });
                toast.classList.add('show');
                bsToast.show();
                toast.addEventListener('hidden.bs.toast', () => toast.remove());
            } catch (e) {
                // If bootstrap toast not available, remove after timeout
                setTimeout(() => toast.remove(), 3000);
            }
        }
        
        // Navbar scrolled shadow behavior
        document.addEventListener('scroll', function() {
            const nav = document.querySelector('.navbar');
            if (!nav) return;
            if (window.scrollY > 4) {
                nav.classList.add('scrolled');
            } else {
                nav.classList.remove('scrolled');
            }
        }, { passive: true });

        // Use Bootstrap's default dropdown behavior; no custom backdrop
    </script>
    <!-- Global theme toggle logic -->
    <script>
        (function(){
            try {
                const storageKey = 'tt-theme';
                const btn = document.getElementById('theme-toggle-global');
                const meta = document.getElementById('meta-theme-color');
                const root = document.documentElement;
                const updateUrl = btn ? btn.getAttribute('data-update-theme-url') : null;

                function currentTheme(){
                    return root.getAttribute('data-theme') || 'light';
                }

                function updateIcon(theme){
                    if (!btn) return;
                    const icon = btn.querySelector('i');
                    if (icon) icon.className = theme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
                    if (typeof i18n !== 'undefined') {
                        btn.setAttribute('aria-label', theme === 'dark' ? i18n.switch_to_light_mode : i18n.switch_to_dark_mode);
                        btn.title = theme === 'dark' ? i18n.light_mode : i18n.dark_mode;
                    } else {
                        btn.setAttribute('aria-label', theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode');
                        btn.title = theme === 'dark' ? 'Light mode' : 'Dark mode';
                    }
                }

                function applyTheme(theme, persist){
                    root.setAttribute('data-theme', theme);
                    if (meta) meta.setAttribute('content', theme === 'dark' ? '#0b1220' : '#3b82f6');
                    updateIcon(theme);
                    if (persist) {
                        try { localStorage.setItem(storageKey, theme); } catch(e) {}
                        if (updateUrl) {
                            try {
                                fetch(updateUrl, {
                                    method: 'POST',
                                    headers: { 'Content-Type': 'application/json' },
                                    body: JSON.stringify({ theme })
                                }).catch(function(){});
                            } catch(e) {}
                        }
                    }
                }

                if (btn) {
                    // Initialize icon to current theme
                    updateIcon(currentTheme());
                    btn.addEventListener('click', function(){
                        const next = currentTheme() === 'dark' ? 'light' : 'dark';
                        applyTheme(next, true);
                    });
                    // Enable tooltip if available
                    try { new bootstrap.Tooltip(btn); } catch(e) {}
                }

                // Keep icon in sync if theme changes elsewhere
                try {
                    new MutationObserver(function(){ updateIcon(currentTheme()); })
                        .observe(root, { attributes: true, attributeFilter: ['data-theme'] });
                } catch(e) {}
            } catch(e) {}
        })();
    </script>

    {% if current_user.is_authenticated %}
    <!-- Socket.IO only for authenticated users -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.js"></script>
    {% endif %}
    {% if request.endpoint != 'auth.login' %}
    <!-- Custom JS (disabled on login to avoid interference) -->
    <script src="{{ url_for('static', filename='mobile.js') }}"></script>
    {% endif %}
    {% if current_user.is_authenticated %}
    <script>
        // Initialize Socket.IO only when logged in
        try {
            const socket = io();
            socket.on('connect', () => console.log('Connected to server'));
            socket.on('disconnect', () => console.log('Disconnected from server'));
            socket.on('timer_started', (data) => {
                showToast(`{{ _('Timer started for') }} ${data.project_name}`, 'success');
                if (typeof updateTimerDisplay === 'function') updateTimerDisplay();
            });
            socket.on('timer_stopped', (data) => {
                showToast(`{{ _('Timer stopped. Duration:') }} ${data.duration}`, 'info');
                if (typeof updateTimerDisplay === 'function') updateTimerDisplay();
            });
            console.log('Base template initialized - Socket.IO and global functions ready');
        } catch (e) {
            console.warn('Socket.IO init failed:', e);
        }
    </script>
    {% endif %}
    
    {% block scripts_extra %}{% endblock %}
    {% block extra_js %}{% endblock %}
    <script>
        // Compact density toggle
        (function(){
            try {
                const key = 'tt-density';
                const saved = localStorage.getItem(key);
                if (saved === 'compact') document.documentElement.classList.add('compact');
                window.toggleDensity = function(){
                    const root = document.documentElement;
                    const isCompact = root.classList.toggle('compact');
                    localStorage.setItem(key, isCompact ? 'compact' : 'comfortable');
                };
            } catch (e) {}
        })();
    </script>
</body>
</html>
