<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{{ title or 'Poultry Management' }}</title>
    
    <!-- PWA Meta Tags -->
    <meta name="description" content="Al Mirag Poultry - Fresh Poultry & Quality Meats. Your trusted source for premium poultry products with comprehensive ordering and delivery system." />
    <meta name="theme-color" content="#4CAF50" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="default" />
    <meta name="apple-mobile-web-app-title" content="Al Mirag Poultry" />
    <meta name="msapplication-TileColor" content="#2E7D32" />
    <meta name="msapplication-tap-highlight" content="no" />
    
    <!-- Enhanced PWA Meta Tags for Universal Compatibility -->
    <meta name="mobile-web-app-capable" content="yes" />
    <meta name="application-name" content="Al Mirag Poultry" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-config" content="none" />
    
    <!-- Open Graph Meta Tags for Social Sharing -->
    <meta property="og:title" content="Al Mirag Poultry Management" />
    <meta property="og:description" content="Fresh Poultry & Quality Meats - Your trusted source for premium poultry products" />
    <meta property="og:type" content="website" />
    <meta property="og:image" content="{{ url_for('static', filename='icons/icon-512x512.png') }}" />
    <meta property="og:url" content="{{ request.url }}" />
    
    <!-- Twitter Card Meta Tags -->
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="Al Mirag Poultry Management" />
    <meta name="twitter:description" content="Fresh Poultry & Quality Meats - Your trusted source for premium poultry products" />
    <meta name="twitter:image" content="{{ url_for('static', filename='icons/icon-512x512.png') }}" />
    
    <!-- PWA Manifest -->
    <link rel="manifest" href="{{ url_for('static', filename='manifest.json') }}" />
    
    <!-- Apple Touch Icons - Enhanced for all iOS devices -->
    <link rel="apple-touch-icon" href="{{ url_for('static', filename='icons/icon-192x192.png') }}" />
    <link rel="apple-touch-icon" sizes="57x57" href="{{ url_for('static', filename='icons/icon-72x72.png') }}" />
    <link rel="apple-touch-icon" sizes="60x60" href="{{ url_for('static', filename='icons/icon-72x72.png') }}" />
    <link rel="apple-touch-icon" sizes="72x72" href="{{ url_for('static', filename='icons/icon-72x72.png') }}" />
    <link rel="apple-touch-icon" sizes="76x76" href="{{ url_for('static', filename='icons/icon-96x96.png') }}" />
    <link rel="apple-touch-icon" sizes="114x114" href="{{ url_for('static', filename='icons/icon-128x128.png') }}" />
    <link rel="apple-touch-icon" sizes="120x120" href="{{ url_for('static', filename='icons/icon-128x128.png') }}" />
    <link rel="apple-touch-icon" sizes="144x144" href="{{ url_for('static', filename='icons/icon-144x144.png') }}" />
    <link rel="apple-touch-icon" sizes="152x152" href="{{ url_for('static', filename='icons/icon-152x152.png') }}" />
    <link rel="apple-touch-icon" sizes="180x180" href="{{ url_for('static', filename='icons/icon-192x192.png') }}" />
    
    <!-- Favicon - Enhanced for all browsers -->
    <link rel="icon" type="image/png" sizes="16x16" href="{{ url_for('static', filename='icons/icon-32x32.png') }}" />
    <link rel="icon" type="image/png" sizes="32x32" href="{{ url_for('static', filename='icons/icon-32x32.png') }}" />
    <link rel="icon" type="image/png" sizes="96x96" href="{{ url_for('static', filename='icons/icon-96x96.png') }}" />
    <link rel="icon" type="image/png" sizes="192x192" href="{{ url_for('static', filename='icons/icon-192x192.png') }}" />
    <link rel="icon" type="image/png" sizes="512x512" href="{{ url_for('static', filename='icons/icon-512x512.png') }}" />
    
    <!-- Legacy favicon -->
    <link rel="shortcut icon" href="{{ url_for('static', filename='icons/icon-32x32.png') }}" />
    
    <!-- Preconnect to external resources -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet" />
    <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}" />
  </head>
  <body>
    <div class="app">
      {% if current_user.is_authenticated %}
        <div class="mobile-overlay" id="mobileOverlay" onclick="closeSidebar()"></div>
        {% include 'partials/sidebar.html' %}
      {% endif %}

      <div class="main">
        <header class="topbar">
          {% if current_user.is_authenticated %}
            <button class="mobile-menu-toggle" onclick="toggleSidebar()" style="display:none;">☰</button>
          {% endif %}
          <div class="brand" onclick="location.href='{{ url_for('dashboard') if current_user.is_authenticated else url_for('index') }}'">🐔 Poultry Manager</div>
          <nav class="topnav">
            <button id="pwa-install-btn" class="install-btn" style="display: none;">
              <i class="fas fa-download"></i> Install App
            </button>
            {% if current_user.is_authenticated %}
              <span class="user">{{ current_user.name }} ({{ current_user.role|capitalize }})</span>
              <a class="btn" href="{{ url_for('logout') }}">Logout</a>
            {% else %}
              <a class="btn" href="{{ url_for('login') }}">Login</a>
            {% endif %}
          </nav>
        </header>

        <main class="content">
          {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
              <div class="flash-container">
                {% for category, message in messages %}
                  <div class="flash {{ category }}">{{ message }}</div>
                {% endfor %}
              </div>
            {% endif %}
          {% endwith %}

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

        <footer class="footer">&copy; {{ now.year }} Poultry Manager</footer>
      </div>
    </div>

    <script src="{{ url_for('static', filename='js/main.js') }}"></script>
    
    <!-- Universal PWA Installation Script -->
    <script src="{{ url_for('static', filename='js/pwa-install.js') }}"></script>
    
    <!-- PWA Service Worker Registration -->
    <script>
      // Register service worker for PWA functionality
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
          navigator.serviceWorker.register('{{ url_for("static", filename="sw.js") }}')
            .then(function(registration) {
              console.log('ServiceWorker registration successful with scope: ', registration.scope);
              
              // Check for updates
              registration.addEventListener('updatefound', function() {
                const newWorker = registration.installing;
                newWorker.addEventListener('statechange', function() {
                  if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                    // New content is available, show update notification
                    if (confirm('New version available! Reload to update?')) {
                      window.location.reload();
                    }
                  }
                });
              });
            })
            .catch(function(err) {
              console.log('ServiceWorker registration failed: ', err);
            });
        });
      }
      
    </script>
    
    <script>
      // Mobile navigation toggle
      function toggleSidebar() {
        const sidebar = document.querySelector('.sidebar');
        const overlay = document.getElementById('mobileOverlay');
        
        if (sidebar.classList.contains('open')) {
          closeSidebar();
        } else {
          openSidebar();
        }
      }
      
      function openSidebar() {
        const sidebar = document.querySelector('.sidebar');
        const overlay = document.getElementById('mobileOverlay');
        
        sidebar.classList.add('open');
        if (overlay) overlay.classList.add('show');
        document.body.style.overflow = 'hidden'; // Prevent background scrolling
      }
      
      function closeSidebar() {
        const sidebar = document.querySelector('.sidebar');
        const overlay = document.getElementById('mobileOverlay');
        
        sidebar.classList.remove('open');
        if (overlay) overlay.classList.remove('show');
        document.body.style.overflow = ''; // Restore scrolling
      }
      
      // Close sidebar when clicking outside on mobile
      document.addEventListener('click', function(event) {
        const sidebar = document.querySelector('.sidebar');
        const toggle = document.querySelector('.mobile-menu-toggle');
        const overlay = document.getElementById('mobileOverlay');
        
        if (window.innerWidth <= 768 && 
            !sidebar.contains(event.target) && 
            !toggle.contains(event.target) && 
            sidebar.classList.contains('open')) {
          closeSidebar();
        }
      });
      
      // Handle window resize
      window.addEventListener('resize', function() {
        const sidebar = document.querySelector('.sidebar');
        const toggle = document.querySelector('.mobile-menu-toggle');
        const overlay = document.getElementById('mobileOverlay');
        
        if (window.innerWidth > 768) {
          closeSidebar();
          if (toggle) toggle.style.display = 'none';
        } else {
          if (toggle) toggle.style.display = 'block';
        }
      });
      
      // Initialize mobile menu toggle visibility
      document.addEventListener('DOMContentLoaded', function() {
        const toggle = document.querySelector('.mobile-menu-toggle');
        if (toggle && window.innerWidth <= 768) {
          toggle.style.display = 'block';
        }
      });
      
      // Close sidebar when clicking on nav links
      document.addEventListener('DOMContentLoaded', function() {
        const navLinks = document.querySelectorAll('.nav-link');
        navLinks.forEach(link => {
          link.addEventListener('click', function() {
            if (window.innerWidth <= 768) {
              closeSidebar();
            }
          });
        });
      });
      
      // Universal Live Search Function
      function initLiveSearch(searchInputId, tableId) {
        const searchInput = document.getElementById(searchInputId);
        if (!searchInput) return;
        
        const table = document.getElementById(tableId);
        if (!table) return;
        
        searchInput.addEventListener('input', function() {
          const filter = this.value.toLowerCase();
          const rows = table.querySelectorAll('tbody tr');
          let visibleCount = 0;
          
          rows.forEach(row => {
            const text = row.textContent.toLowerCase();
            if (text.includes(filter)) {
              row.style.display = '';
              visibleCount++;
            } else {
              row.style.display = 'none';
            }
          });
          
          // Show/hide "no results" message
          let noResultsRow = table.querySelector('.no-results-row');
          if (visibleCount === 0 && filter.length > 0) {
            if (!noResultsRow) {
              noResultsRow = document.createElement('tr');
              noResultsRow.className = 'no-results-row';
              noResultsRow.innerHTML = '<td colspan="100%" class="muted" style="text-align: center; padding: 32px;">No results found</td>';
              table.querySelector('tbody').appendChild(noResultsRow);
            }
            noResultsRow.style.display = '';
          } else if (noResultsRow) {
            noResultsRow.style.display = 'none';
          }
        });
      }
    </script>
  </body>
  </html>


