<!DOCTYPE html>
<html lang="pt-BR">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Cardápio Digital</title>
    <meta name="description" content="Veja nosso cardápio e faça seu pedido de forma segura e rápida 🍽️" />
    <meta name="author" content="Guipo Sistemas" />
    
    <!-- PWA Meta Tags
         Cardápio: no boot, theme-color do cache do header (localStorage) quando existir —
         evita faixa branca / progress L→R entre status bar e header no reload.
         Sem cache: sem meta (fallback preto). Admin: #111827. Garçom: waiter-theme → branco/#1a1a1e. -->
    <meta name="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="Cardápio" />
    
    <!-- PWA Icons — mesmo arquivo do manifest (pwa-icon-*); troque só esses PNGs em public/ -->
    <link rel="icon" type="image/png" href="/pwa-icon-192-v6.png" data-favicon-key="pwa" />
    <link rel="shortcut icon" type="image/png" href="/pwa-icon-192-v6.png" />
    <link rel="apple-touch-icon" sizes="192x192" href="/pwa-icon-192-v6.png" />
    
    <!-- PWA Manifest + captura do prompt antes do React (cardápio / admin / garçom) -->
    <link rel="manifest" href="/manifest.json" id="pwa-manifest-link" />
    <script>
      (function () {
        var MENU_HEADER_THEME_KEY = 'guipo-menu-header-theme';

        function manifestForPath(pathname) {
          pathname = pathname || '/';
          if (pathname.indexOf('/admin') === 0) return '/manifest-admin.json';
          if (pathname.indexOf('/garcom') === 0) return '/manifest-garcom.json';
          return '/manifest.json';
        }

        function applyManifest(pathname) {
          var href = manifestForPath(pathname);
          var link = document.getElementById('pwa-manifest-link');
          if (link) link.setAttribute('href', href);
          return href;
        }

        function upsertThemeColor(content) {
          var themeMeta = document.querySelector('meta[name="theme-color"]');
          if (!themeMeta) {
            themeMeta = document.createElement('meta');
            themeMeta.setAttribute('name', 'theme-color');
            document.head.appendChild(themeMeta);
          }
          themeMeta.setAttribute('content', content);
        }

        function clearThemeColor() {
          document.querySelectorAll('meta[name="theme-color"]').forEach(function (meta) {
            meta.parentNode && meta.parentNode.removeChild(meta);
          });
        }

        function parseHex(hex) {
          var raw = String(hex || '').trim().replace('#', '');
          if (raw.length === 3) {
            raw = raw.split('').map(function (c) { return c + c; }).join('');
          }
          if (!/^[0-9a-fA-F]{6}$/.test(raw)) return null;
          return {
            r: parseInt(raw.slice(0, 2), 16),
            g: parseInt(raw.slice(2, 4), 16),
            b: parseInt(raw.slice(4, 6), 16),
          };
        }

        function mixRgb(a, b, t) {
          return {
            r: Math.round(a.r + (b.r - a.r) * t),
            g: Math.round(a.g + (b.g - a.g) * t),
            b: Math.round(a.b + (b.b - a.b) * t),
          };
        }

        function toHex(c) {
          return '#' + [c.r, c.g, c.b].map(function (n) {
            return n.toString(16).padStart(2, '0');
          }).join('');
        }

        /** Espelho de headerStatusBarColor (src/lib/headerStatusBarColor.ts). */
        function headerStatusBarColor(primary, secondary, headerStyle) {
          var p = parseHex(primary || '#FF6B35');
          if (!p) return String(primary || '#FF6B35').trim();
          var s = parseHex(secondary || '#F7931E') || p;
          var base = headerStyle === 'gradient' ? mixRgb(p, s, 0.18) : p;
          return toHex(mixRgb(base, { r: 0, g: 0, b: 0 }, 0.1));
        }

        function readCachedMenuTheme() {
          var host = 'default';
          try { host = window.location.hostname || 'default'; } catch (e) { /* ignore */ }
          var key = MENU_HEADER_THEME_KEY + ':' + host;
          try {
            var local = localStorage.getItem(key);
            if (local) return JSON.parse(local);
          } catch (e) { /* ignore */ }
          try {
            var session = sessionStorage.getItem(key);
            if (session) return JSON.parse(session);
          } catch (e) { /* ignore */ }
          try {
            var legacy = sessionStorage.getItem(MENU_HEADER_THEME_KEY);
            if (legacy) return JSON.parse(legacy);
          } catch (e) { /* ignore */ }
          return null;
        }

        function clearBootPaint() {
          try {
            document.documentElement.style.removeProperty('background-color');
            document.documentElement.removeAttribute('data-boot-theme-paint');
            if (document.body) document.body.style.removeProperty('background-color');
          } catch (e) { /* ignore */ }
        }

        function applyBootPaint(color) {
          if (!color) return;
          try {
            document.documentElement.style.backgroundColor = color;
            document.documentElement.setAttribute('data-boot-theme-paint', '1');
            if (document.body) document.body.style.backgroundColor = color;
          } catch (e) { /* ignore */ }
        }

        function applyThemeForPath(pathname) {
          pathname = pathname || '/';
          if (pathname.indexOf('/admin') === 0) {
            upsertThemeColor('#111827');
            document.title = 'Admin Cardápio';
            var appleTitle = document.querySelector('meta[name="apple-mobile-web-app-title"]');
            if (appleTitle) appleTitle.setAttribute('content', 'Admin');
          } else if (pathname.indexOf('/garcom') === 0) {
            // Alinha status bar + paint ao header (bg-background), não ao laranja de marca.
            var waiterDark = false;
            try {
              waiterDark = localStorage.getItem('waiter-theme') === 'dark';
            } catch (e) { /* ignore */ }
            // Espelho de --background do .waiter-theme (index.css)
            var waiterColor = waiterDark ? '#18181b' : '#fafafa';
            upsertThemeColor(waiterColor);
            applyBootPaint(waiterColor);
            document.title = 'App Garçom';
            var waiterAppleTitle = document.querySelector('meta[name="apple-mobile-web-app-title"]');
            if (waiterAppleTitle) waiterAppleTitle.setAttribute('content', 'App Garçom');
          } else {
            // Cardápio: cache do header → theme-color imediato (sem faixa branca no reload).
            // Sem cache (1ª visita): sem meta → fallback preto até o React.
            var cached = readCachedMenuTheme();
            var primary = cached && cached.primary ? String(cached.primary).trim() : '';
            if (primary) {
              var color = headerStatusBarColor(
                primary,
                cached.secondary,
                cached.headerStyle
              );
              upsertThemeColor(color);
              applyBootPaint(color);
            } else {
              clearThemeColor();
            }
          }
        }

        applyManifest(window.location.pathname);
        applyThemeForPath(window.location.pathname);
        window.__PWA_DEFERRED_PROMPTS__ = window.__PWA_DEFERRED_PROMPTS__ || {};
        window.addEventListener('app-shell-ready', clearBootPaint);
        document.addEventListener('DOMContentLoaded', function () {
          if (document.documentElement.getAttribute('data-boot-theme-paint') === '1') {
            applyBootPaint(document.documentElement.style.backgroundColor);
          }
        });

        if ((window.location.pathname || '/').indexOf('/admin') === 0) {
          document.documentElement.classList.add('font-admin');
          if (!document.getElementById('admin-inter-font')) {
            var adminFont = document.createElement('link');
            adminFont.id = 'admin-inter-font';
            adminFont.rel = 'stylesheet';
            adminFont.href = 'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap';
            document.head.appendChild(adminFont);
          }
        }

        window.addEventListener('beforeinstallprompt', function (e) {
          e.preventDefault();
          var href = applyManifest(window.location.pathname);
          window.__PWA_DEFERRED_PROMPTS__[href] = e;
          try {
            sessionStorage.setItem('pwa-deferred-prompt-' + href, 'true');
          } catch (err) {
            /* ignore */
          }
        });

        if ('serviceWorker' in navigator) {
          navigator.serviceWorker.register('/sw.js', { scope: '/' }).catch(function () {});
        }
      })();
    </script>

    <meta property="og:title" content="Cardápio Digital" />
    <meta property="og:description" content="Veja nosso cardápio e faça seu pedido de forma segura e rápida 🍽️" />
    <meta property="og:type" content="website" />
    <meta property="og:image" content="/share-image-v6.png" />
    <meta property="og:image:width" content="1200" />
    <meta property="og:image:height" content="630" />

    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:site" content="@guipo_sistemas" />
    <meta name="twitter:image" content="/share-image-v6.png" />
    
    <!-- Content Security Policy - Proteção contra XSS -->
    <meta http-equiv="Content-Security-Policy" content="
      default-src 'self';
      script-src 'self' 'unsafe-inline' 'unsafe-eval' https://*.supabase.co https://*.supabase.in https://*.guiposistemas.com.br;
      style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
      font-src 'self' https://fonts.gstatic.com data:;
      img-src 'self' data: https: blob:;
      connect-src 'self' https://*.supabase.co https://*.supabase.in https://*.guiposistemas.com.br wss://*.supabase.co wss://*.supabase.in wss://*.guiposistemas.com.br;
      frame-src 'self' https://*.supabase.co https://*.guiposistemas.com.br;
      object-src 'none';
      base-uri 'self';
      form-action 'self';
      upgrade-insecure-requests;
    " />
    <script type="module" crossorigin src="/assets/index-BJ-yNTge.js"></script>
    <link rel="stylesheet" crossorigin href="/assets/index-DITrd28l.css">
  </head>

  <body>
    <div id="root"></div>
    <script>
      (function () {
        const OVERLAY_ID = 'app-recovery-overlay';
        const RESUME_CHECK_DELAY_MS = 6000;
        const RESUME_MAX_RETRIES = 2;
        let resumeTimer = null;
        let resumeRetryCount = 0;
        let hasEverMountedShell = false;

        function isStandalone() {
          return window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true;
        }

        function hasMountedAppShell() {
          const root = document.getElementById('root');
          return Boolean(root && root.querySelector('[data-app-shell-ready="true"]'));
        }

        function isReactMounting() {
          const root = document.getElementById('root');
          return Boolean(root && root.childElementCount > 0 && !hasMountedAppShell());
        }

        function removeRecoveryOverlay() {
          const existing = document.getElementById(OVERLAY_ID);
          if (existing) existing.remove();
        }

        function createRecoveryOverlay(reason) {
          if (document.getElementById(OVERLAY_ID)) return;

          const overlay = document.createElement('div');
          overlay.id = OVERLAY_ID;
          overlay.setAttribute('role', 'alertdialog');
          overlay.setAttribute('aria-live', 'assertive');
          overlay.style.position = 'fixed';
          overlay.style.inset = '0';
          overlay.style.zIndex = '99999';
          overlay.style.display = 'flex';
          overlay.style.alignItems = 'center';
          overlay.style.justifyContent = 'center';
          overlay.style.padding = '16px';
          overlay.style.background = 'rgba(2, 6, 23, 0.92)';

          const panel = document.createElement('div');
          panel.style.width = '100%';
          panel.style.maxWidth = '420px';
          panel.style.borderRadius = '24px';
          panel.style.border = '1px solid rgba(255,255,255,0.08)';
          panel.style.background = 'rgba(15, 23, 42, 0.96)';
          panel.style.boxShadow = '0 25px 50px rgba(0,0,0,0.35)';
          panel.style.padding = '24px';
          panel.style.color = '#fff';
          panel.innerHTML =
            '<div style="display:inline-flex;height:48px;width:48px;align-items:center;justify-content:center;border-radius:16px;background:rgba(249,115,22,0.16);color:#fdba74;font-size:22px;font-weight:700;">!</div>' +
            '<h1 style="margin:16px 0 8px;font-size:20px;line-height:28px;font-weight:600;">Nao foi possivel restaurar o aplicativo</h1>' +
            '<p style="margin:0 0 20px;font-size:14px;line-height:22px;color:#cbd5e1;">O APP encontrou uma falha ao voltar do segundo plano. Recarregue para continuar com seguranca.</p>';

          const button = document.createElement('button');
          button.type = 'button';
          button.textContent = 'Recarregar aplicativo';
          button.style.width = '100%';
          button.style.border = '0';
          button.style.borderRadius = '16px';
          button.style.background = '#f97316';
          button.style.color = '#fff';
          button.style.cursor = 'pointer';
          button.style.fontSize = '14px';
          button.style.fontWeight = '600';
          button.style.padding = '14px 16px';
          button.addEventListener('click', function () {
            window.location.reload();
          });

          const helper = document.createElement('p');
          helper.style.margin = '14px 0 0';
          helper.style.fontSize = '12px';
          helper.style.lineHeight = '18px';
          helper.style.color = '#94a3b8';
          helper.textContent = 'Se o problema persistir, feche o APP e abra novamente pela tela inicial do aparelho.';

          panel.appendChild(button);
          panel.appendChild(helper);
          overlay.appendChild(panel);
          document.body.appendChild(overlay);

          console.error('[PWARecovery] Overlay de recuperacao exibido', {
            reason,
            standalone: isStandalone(),
          });
        }

        function scheduleResumeHealthCheck(reason) {
          if (!isStandalone()) return;
          if (!hasEverMountedShell) return;

          if (resumeTimer) {
            clearTimeout(resumeTimer);
          }

          resumeTimer = setTimeout(function () {
            resumeTimer = null;
            if (hasMountedAppShell()) {
              resumeRetryCount = 0;
              removeRecoveryOverlay();
              return;
            }

            if (isReactMounting() && resumeRetryCount < RESUME_MAX_RETRIES) {
              resumeRetryCount += 1;
              scheduleResumeHealthCheck(reason + ':react-mount-retry');
              return;
            }

            resumeRetryCount = 0;
            createRecoveryOverlay(reason);
          }, RESUME_CHECK_DELAY_MS);
        }

        window.__APP_RECOVERY__ = {
          hide: removeRecoveryOverlay,
          show: createRecoveryOverlay,
          scheduleCheck: scheduleResumeHealthCheck,
        };

        window.addEventListener('pageshow', function () {
          scheduleResumeHealthCheck('pageshow');
        });

        document.addEventListener('visibilitychange', function () {
          if (document.visibilityState === 'visible') {
            scheduleResumeHealthCheck('visibilitychange');
          }
        });

        window.addEventListener('app-shell-ready', function () {
          hasEverMountedShell = true;
          resumeRetryCount = 0;
          removeRecoveryOverlay();
        });

        window.addEventListener('app-shell-unmounted', function () {
          scheduleResumeHealthCheck('app-shell-unmounted');
        });

        window.addEventListener('app-recovery-needed', function (event) {
          if (!isStandalone()) return;
          createRecoveryOverlay(event && event.detail && event.detail.source ? event.detail.source : 'runtime-error');
        });
      })();
    </script>
  </body>
</html>
