{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}SwiftPOS{% endblock %}</title>
    <link rel="icon" type="image/x-icon" href="{% static 'core/icons/favicon.ico' %}">
    
    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/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">
    <link rel="manifest" href="{% static 'core/manifest.webmanifest' %}">
    <link rel="apple-touch-icon" href="{% static 'core/icons/icon-192.png' %}">
    
    <!-- Inter + Outfit Fonts (SaaS Modern) -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=Outfit:wght@700;800;900&display=swap" rel="stylesheet">

    <!-- SwiftPOS CSS -->
    <link rel="stylesheet" href="{% static 'css/style.css' %}?v=12">
    <!-- Responsive nav patch -->
    <link rel="stylesheet" href="{% static 'css/responsive_nav_patch.css' %}?v=1">

    <link rel="manifest" href="{% static 'core/manifest.webmanifest' %}">
    <link rel="apple-touch-icon" href="{% static 'core/icons/icon-192.png' %}">
    <meta name="theme-color" content="#6d28d9">

    {% block extra_css %}{% endblock %}
</head>
<body class="swiftpos-body">
<script>
// ══ Global SwiftPOS JS Variables (injected from contexts) ══
window.swiftposCompanySlug = "{% if request.company %}{{ request.company.slug|escapejs }}{% endif %}";
window.swiftposCurrencySymbol = "{{ currency_symbol|escapejs }}";
window.swiftposVatRate = {{ vat_rate|floatformat:2 }};
window.swiftposDecimalPlaces = {{ decimal_places }};
window.swiftposUseCommaSeparator = {{ use_comma_separator|yesno:"true,false" }};
window.swiftposProductsApiUrl = "{% url 'inventory:product_list_json' %}";
window.swiftposScanApiUrl = "{% url 'sales:api_scan_barcode' %}";
window.swiftposOrdersApiUrl = "{% url 'sales:api_create_order' %}";


/**
 * SwiftPOS global currency formatter.
 * Uses the company's currency symbol and comma-separator setting.
 *
 * @param {number|string} value - The numeric value to format
 * @param {number} [dp] - Decimal places (defaults to swiftposDecimalPlaces)
 * @param {boolean} [withSymbol] - Prepend currency symbol (default: true)
 * @returns {string} e.g. "₦1,250.00" or "1250.00"
 */
window.swiftposFormatMoney = function(value, dp, withSymbol) {
    var decimals = (dp !== undefined) ? dp : (window.swiftposDecimalPlaces || 2);
    var useComma = window.swiftposUseCommaSeparator !== false;
    var num = parseFloat(value) || 0;
    var formatted;
    if (useComma) {
        formatted = num.toLocaleString('en-US', {
            minimumFractionDigits: decimals,
            maximumFractionDigits: decimals
        });
    } else {
        formatted = num.toFixed(decimals);
    }
    if (withSymbol === false) return formatted;
    return (window.swiftposCurrencySymbol || '₦') + formatted;
};

// Short alias
window.fmtMoney = window.swiftposFormatMoney;
</script>

<!-- ══ GLOBAL TOASTS (from Django messages) ══ -->
<!-- <div class="swiftpos-toast-container" id="swiftpos-global-toast-container">
    {% if messages %}
        {% for message in messages %}
            <div class="swiftpos-toast swiftpos-toast-{{ message.tags }}" onclick="this.remove()">
                <div class="toast-icon">
                    {% if 'success' in message.tags %}<i class="fas fa-check-circle"></i>
                    {% elif 'error' in message.tags or 'danger' in message.tags %}<i class="fas fa-exclamation-circle"></i>
                    {% elif 'warning' in message.tags %}<i class="fas fa-exclamation-triangle"></i>
                    {% else %}<i class="fas fa-info-circle"></i>{% endif %}
                </div>
                <div class="toast-text">{{ message }}</div>
            </div>
        {% endfor %}
    {% endif %}
</div> -->

<div class="swiftpos-app d-flex">

    <!-- SIDEBAR -->
    <aside id="swiftposSidebar" class="swiftpos-sidebar">
        <div class="sidebar-inner d-flex flex-column h-100">

            <!-- Brand -->
            <div class="sidebar-header d-flex align-items-center justify-content-between">
                <a href="{% url 'dashboard' %}" class="sidebar-brand d-flex align-items-center text-decoration-none">
                    <div class=" d-flex align-items-center justify-content-center">
                        {% load static %}
                      <img
                        src="{% static 'core/icons/icon-192.png' %}"
                        alt="SwiftPOS logo"
                        class="brand-logo-img me-2"
                      />
                    </div>
                   <div>  <!--  class="brand-text ms-2" -->
                        <span  class="brand-title">SwiftPOS</span>
                        <!-- <span class="brand-subtitle">Fast. Simple. Clear.</span> -->
                    </div>
                </a>

                <!-- Desktop collapse -->
                <button id="sidebarToggle"
                        class="btn btn-sm btn-outline-light d-none d-lg-inline-flex sidebar-toggle-btn"
                        type="button">
                    <i class="fas fa-chevron-left"></i>
                </button>
            </div>

            <!-- User -->
            <div class="sidebar-user mt-2">
                <div class="user-avatar" id="sidebar-user-avatar">
                    {{ user.get_full_name|default:user.username|slice:':2'|upper }}
                </div>
                <div class="user-meta">
                    <div class="user-name">{{ user.get_full_name|default:user.username }}</div>
                    {% if user.get_role_display %}
                        <div class="user-role">{{ user.get_role_display }}</div>
                    {% endif %}
                </div>
            </div>

            {% with current_url_name=request.resolver_match.url_name %}

            <!-- NAV -->
            <nav class="sidebar-nav flex-grow-1 mt-2">

                <div class="sidebar-section-label">Overview</div>
                {% if user.role == 'admin' or user.role == 'manager' %}
                <a href="{% url 'dashboard' %}"
                   class="sidebar-link {% if current_url_name == 'dashboard' %}active{% endif %}">
                    <span class="icon"><i class="fas fa-gauge"></i></span>
                    <span class="label">Dashboard</span>
                </a>
                {% endif %}

                <a href="{% url 'sales_hub' %}"
                   class="sidebar-link {% if 'sales-hub' in request.path or 'sales' in current_url_name %}active{% endif %}">
                    <span class="icon"><i class="fas fa-shopping-cart"></i></span>
                    <span class="label">Sales Room</span>
                </a>

                {% if user.role == 'admin' or user.role == 'manager' %}
                <a href="{% url 'inventory_hub' %}"
                   class="sidebar-link {% if 'inventory-hub' in request.path or 'inventory' in current_url_name %}active{% endif %}">
                    <span class="icon"><i class="fas fa-boxes"></i></span>
                    <span class="label">Inventory</span>
                </a>
                {% endif %}

                <a href="{% url 'insights_hub' %}"
                   class="sidebar-link {% if 'insights-hub' in request.path or 'analytics' in current_url_name or 'current_url_name' == 'pnl_report' %}active{% endif %}">
                    <span class="icon"><i class="fas fa-chart-pie"></i></span>
                    <span class="label">Insights Hub</span>
                </a>

                {% if user.role == 'admin' %}
                <a href="{% url 'admin_hub' %}"
                   class="sidebar-link {% if 'admin-hub' in request.path or 'settings' in current_url_name or 'branch' in current_url_name or 'role' in current_url_name %}active{% endif %}">
                    <span class="icon"><i class="fas fa-cog"></i></span>
                    <span class="label">Admin Center</span>
                </a>
                {% endif %}

                <!-- Subscription (visible to admin) -->
                {% if user.role == 'admin' %}
                <div class="sidebar-section-label mt-3">Subscription</div>
                <a href="{% url 'subscriptions:manage' %}"
                   class="sidebar-link {% if request.resolver_match.namespace == 'subscriptions' %}active{% endif %}">
                    <span class="icon"><i class="fas fa-bolt"></i></span>
                    <span class="label">My Subscription</span>
                </a>
                {% endif %}

            </nav>
            {% endwith %}

            <!-- LOGOUT -->
            <button id="install-app-btn"
        class="btn btn-sm btn-outline-light d-none"
        type="button">
    Install App
</button>
            <div class="sidebar-footer mt-auto p-2">
                <a href="{% url 'logout' %}" class="sidebar-link logout-link">
                    <span class="icon"><i class="fas fa-sign-out-alt"></i></span>
                    <span class="label">Logout</span>
                </a>
            </div>
        </div>
    </aside>

    <!-- MAIN -->
    <div class="swiftpos-main d-flex flex-column flex-grow-1">
<header class="swiftpos-topbar">
            <div class="d-flex align-items-center gap-2">
                <!-- Mobile Hamburger -->
                <button id="mobileSidebarToggle"
                        class="btn btn-sm btn-outline-secondary d-inline-flex d-lg-none"
                        type="button" style="border-radius:8px;">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="topbar-title">
                    {% block topbar_title %}Dashboard{% endblock %}
                </div>
            </div>

            <!-- Right side -->
            <div class="d-flex align-items-center gap-2">
<!-- View Plan badge (admin only) -->
                {% if user.role == 'admin' %}
                <a href="{% url 'subscriptions:manage' %}"
                   class="btn btn-sm d-none d-md-flex align-items-center gap-1"
                   style="border-radius:8px;font-size:.75rem;font-weight:700;
                          background:linear-gradient(135deg,#ede9fe,#ddd6fe);
                          color:#6d28d9;border:none;white-space:nowrap;"
                   title="View Subscription Plan">
                    <i class="fas fa-bolt"></i>
                    <span>{{ plan_name }}</span>
                </a>
                {% endif %}

                <!-- Quick POS shortcut -->
                {% if user.role == 'admin' or user.role == 'manager' or user.role == 'cashier' %}
                <a href="{% if pos_interface_mode == 'grid' %}{% url 'sales:pos_grid' %}{% else %}{% url 'sales:pos' %}{% endif %}"
                   class="sp-pos-quick-btn d-none d-sm-flex">
                    <i class="fas fa-cash-register"></i> POS
                </a>
                {% endif %}

                <!-- Today shortcut -->
                <a href="{% url 'sales:daily_dashboard' %}" class="btn btn-sm btn-light d-none d-md-flex align-items-center gap-1" style="border-radius:8px;font-size:.78rem;">
                    <i class="fas fa-calendar-day" style="color:#7c3aed"></i>
                    <span>Today</span>
                </a>

                <!-- Custom AI Chat Button -->
                <a href="{% url 'web_ai_chat' %}" class="btn btn-sm text-white d-flex align-items-center gap-1" style="background: linear-gradient(135deg, #a78bfa, #8b5cf6); border-radius:8px; font-size:.78rem;" title="AI Assistant">
                    <i class="fas fa-sparkles"></i>
                    <span>AI Brain</span>
                </a>

                <!-- Google Translate (Commented out per request) -->
                <!--
                <div id="gt-wrapper" title="Translate this page">
                    <i class="fas fa-globe"></i>
                    <span class="d-none d-sm-inline">Translate</span>
                    <div id="google_translate_element"></div>
                </div>
                -->

                <!-- User dropdown -->
                <div class="dropdown">
                    <button class="topbar-user-btn" data-bs-toggle="dropdown">
                        <div class="topbar-user-avatar">
                            {{ user.get_full_name|default:user.username|slice:':2'|upper }}
                        </div>
                        <span class="d-none d-sm-inline" style="font-size:.82rem;font-weight:600;color:#374151;">{{ user.username }}</span>
                        <i class="fas fa-chevron-down" style="font-size:.6rem;color:#9ca3af;"></i>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end shadow" style="border-radius:12px;border-color:#e5e7eb;min-width:200px;">
                        <li class="px-3 py-2">
                            <div style="font-weight:600;font-size:.85rem;color:#0f172a;">{{ user.get_full_name|default:user.username }}</div>
                            {% if user.get_role_display %}
                            <div style="font-size:.72rem;color:#9ca3af;">{{ user.get_role_display }}</div>
                            {% endif %}
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        {% if user.role == 'admin' %}
                        <li>
                            <a class="dropdown-item d-flex align-items-center gap-2" href="{% url 'system_settings' %}" style="font-size:.82rem;">
                                <i class="fas fa-sliders-h" style="width:14px;color:#9ca3af;"></i> Settings
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item d-flex align-items-center gap-2" href="{% url 'sales:end_of_day' %}" style="font-size:.82rem;">
                                <i class="fas fa-cash-register" style="width:14px;color:#9ca3af;"></i> End of Day
                            </a>
                        </li>
                        {% endif %}
                        <li>
                            <a class="dropdown-item d-flex align-items-center gap-2 text-danger" href="{% url 'logout' %}" style="font-size:.82rem;">
                                <i class="fas fa-sign-out-alt" style="width:14px;"></i> Logout
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </header>

                <!-- ══ DESKTOP TOP NAV (lg+) ══ -->
        <nav class="sp-topnav" id="sp-topnav">

            <a href="{% url 'dashboard' %}" class="sp-topnav-link {% if request.resolver_match.url_name == 'dashboard' %}active{% endif %}" style="text-decoration:none;">
                <i class="fas fa-gauge"></i> Overview
            </a>

            <a href="{% url 'sales_hub' %}" class="sp-topnav-link {% if 'sales-hub' in request.path or 'sales' in request.resolver_match.url_name %}active{% endif %}" style="text-decoration:none;">
                <i class="fas fa-shopping-cart"></i> Sales Room
            </a>

            {% if user.role == 'admin' or user.role == 'manager' %}
            <a href="{% url 'inventory_hub' %}" class="sp-topnav-link {% if 'inventory-hub' in request.path or 'inventory' in request.resolver_match.url_name %}active{% endif %}" style="text-decoration:none;">
                <i class="fas fa-boxes"></i> Inventory
            </a>
            {% endif %}

            <a href="{% url 'insights_hub' %}" class="sp-topnav-link {% if 'insights-hub' in request.path or 'analytics' in request.resolver_match.namespace or request.resolver_match.url_name == 'pnl_report' %}active{% endif %}" style="text-decoration:none;">
                <i class="fas fa-chart-pie"></i> Insights Hub
            </a>

            {% if user.role == 'admin' %}
            <a href="{% url 'admin_hub' %}" class="sp-topnav-link {% if 'admin-hub' in request.path or 'settings' in request.resolver_match.url_name or 'branch' in request.resolver_match.url_name or 'role' in request.resolver_match.url_name %}active{% endif %}" style="text-decoration:none;">
                <i class="fas fa-cog"></i> Admin Center
            </a>
            {% endif %}

            <!-- Quick POS button in nav bar -->
            {% if user.role == 'admin' or user.role == 'manager' or user.role == 'cashier' %}
            <a href="{% if pos_interface_mode == 'grid' %}{% url 'sales:pos_grid' %}{% else %}{% url 'sales:pos' %}{% endif %}"
               class="sp-pos-quick-btn ms-auto my-auto" style="height: 38px; display:flex; align-items:center;">
                <i class="fas fa-cash-register"></i> Open POS
            </a>
            {% endif %}

        </nav><!-- /sp-topnav -->

        <!-- ══ PAGE CONTENT ══ -->
        <main class="swiftpos-content flex-grow-1">
            <div class="container-fluid py-3">
               

                {% block content %}{% endblock %}
            </div>
        </main>

        <!-- FOOTER -->
        <footer class="swiftpos-footer py-2">
            <div class="container-fluid d-flex justify-content-between small">
                <span>&copy; {% now "Y" %} SwiftPOS</span>
                <span class="text-muted">Fast. Simple & Clear.</span>
            </div>
        </footer>

    </div>
</div>

<!-- Mobile Overlay -->
<div id="sidebarOverlay" class="swiftpos-overlay d-lg-none"></div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- jQuery (required by Select2) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Add these lines inside the <head> section of base.html -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<!-- SIDEBAR SCRIPT -->

<script>
document.addEventListener('DOMContentLoaded', function () {
    const toasts = document.querySelectorAll('.swiftpos-toast');
    toasts.forEach((toast) => {
        setTimeout(() => {
            toast.style.animation = 'toast-out 0.25s ease-in forwards';
            setTimeout(() => toast.remove(), 250);
        }, 2000); // 2 seconds
    });
});
</script>

<script>
(function () {
    const sidebar = document.getElementById("swiftposSidebar");
    const desktopToggle = document.getElementById("sidebarToggle");
    const mobileToggle = document.getElementById("mobileSidebarToggle");
    const overlay = document.getElementById("sidebarOverlay");
    const KEY = "swiftpos_sidebar_collapsed";

    if (desktopToggle) {
        desktopToggle.addEventListener("click", function () {
            sidebar.classList.toggle("collapsed");
            try {
                localStorage.setItem(KEY, sidebar.classList.contains("collapsed") ? "1" : "0");
            } catch (e) {}
        });
    }

    try {
        if (localStorage.getItem(KEY) === "1") {
            sidebar.classList.add("collapsed");
        }
    } catch (e) {}

    if (mobileToggle) {
        mobileToggle.addEventListener("click", function () {
            document.body.classList.toggle("sidebar-mobile-open");
        });
    }

    if (overlay) {
        overlay.addEventListener("click", function () {
            document.body.classList.remove("sidebar-mobile-open");
        });
    }
})();
</script>

<script>
(function () {
    const contentSections = document.querySelectorAll(".swiftpos-content");
    const cards = document.querySelectorAll(".swiftpos-content .card, .swiftpos-content .metric-card");

    // Mark containers & cards for animation
    contentSections.forEach(section => {
        section.classList.add("sp-animate-section");
    });

    cards.forEach((card, index) => {
        card.classList.add("sp-animate-card");
        // we store an index so we can stagger the delay
        card.dataset.spAnimIndex = String(index);
    });

    function revealImmediately() {
        contentSections.forEach(section => {
            section.classList.add("sp-animate-visible");
        });
        cards.forEach(card => {
            card.classList.add("sp-animate-visible");
        });
    }

    if (!("IntersectionObserver" in window)) {
        // Old browsers: show immediately, no animation logic
        revealImmediately();
        return;
    }

    // Observe cards for staggered reveal
    const cardObserver = new IntersectionObserver(
        (entries) => {
            entries.forEach((entry) => {
                if (!entry.isIntersecting) return;

                const el = entry.target;
                const idx = parseInt(el.dataset.spAnimIndex || "0", 10);
                const delayMs = Math.min(idx * 50, 400); // max 0.4s

                el.style.transitionDelay = delayMs + "ms";
                el.classList.add("sp-animate-visible");
                cardObserver.unobserve(el);
            });
        },
        {
            threshold: 0.02,
            rootMargin: "50px"
        }
    );

    cards.forEach((card) => cardObserver.observe(card));

    // Observe main content containers
    const sectionObserver = new IntersectionObserver(
        (entries) => {
            entries.forEach((entry) => {
                if (!entry.isIntersecting) return;
                entry.target.classList.add("sp-animate-visible");
                sectionObserver.unobserve(entry.target);
            });
        },
        {
            threshold: 0.02,
            rootMargin: "50px"
        }
    );

    contentSections.forEach((section) => sectionObserver.observe(section));
})();
</script>
 <script src="{% static 'js/pwa.js' %}"></script>

<!-- <script src="{% static 'js/html2canvas.min.js' %}"></script>
<script src="{% static 'js/receipt_actions.js' %}"></script>
 -->


<script>
// GLOBAL SwiftPOS Modal Function
window.swiftposAlert = function(message) {
    const overlay = document.getElementById("swiftpos-modal-overlay");
    const msgBox = document.getElementById("swiftpos-modal-message");
    const btn = document.getElementById("swiftpos-modal-btn");

    msgBox.textContent = message;
    overlay.classList.remove("d-none");

    btn.onclick = () => overlay.classList.add("d-none");
};
</script>

{% block extra_js %}{% endblock %}

<script>
// Auto-dismiss toasts after 4 seconds
document.addEventListener('DOMContentLoaded', function () {
    const container = document.getElementById('swiftpos-global-toast-container');
    if (!container) return;
    const toasts = container.querySelectorAll('.swiftpos-toast');
    toasts.forEach((toast, i) => {
        setTimeout(() => {
            toast.style.animation = 'toast-out 0.3s ease-in forwards';
            setTimeout(() => toast.remove(), 300);
        }, 3500 + i * 500);
    });
});
</script>

<!-- SwiftPOS Modal -->
<div id="swiftpos-modal-overlay" class="swiftpos-modal-overlay d-none">
    <div id="swiftpos-modal" class="swiftpos-modal">
        <div class="modal-header-area">
            <span class="modal-title">SwiftPOS</span>
        </div>
        <div class="modal-body-area">
            <p id="swiftpos-modal-message"></p>
        </div>
        <div class="modal-footer-area">
            <button id="swiftpos-modal-btn" class="btn btn-primary w-100">OK</button>
        </div>
    </div>
</div>

<!-- ░░░ Google Translate Widget ░░░ -->
<script type="text/javascript">
function googleTranslateElementInit() {
    new google.translate.TranslateElement({
        pageLanguage: 'en',
        includedLanguages: 'en,fr,es,de,zh-CN,ar,hi,pt,ru,sw,ha,yo,ig,zu,am',
        layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
        autoDisplay: false,
        multilanguagePage: true,
    }, 'google_translate_element');
}
</script>
<script type="text/javascript"
        src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"
        async defer></script>

<!-- AI widget removed in favor of full page -->
</body>
</html>