<!DOCTYPE html>
<html lang="pt-BR">
  <head>
        <script>
          window.SUPABASE_URL = 'https://crhjgygsjssfnmihhjav.supabase.co';
          window.SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImNyaGpneWdzanNzZm5taWhoamF2Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDkyMzYwODMsImV4cCI6MjA2NDgxMjA4M30._rXYRLQPS6mIjVGl9ez-ACFvwRrOsiOWLWMQTFrCzYU';
        </script>
      
    <meta charset="UTF-8" />
    
    <!-- 🍎 ULTRA PRIORITY: Safari Mobile Fix - EXECUTA ANTES DE TUDO -->
    <!-- REMOVIDO BLOCO DE REDIRECIONAMENTO PARA F42183A1.PAGES.DEV -->
    
    <link rel="icon" type="image/svg+xml" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
    <title>ResultCrop - Relatórios Agrícolas</title>
    <meta name="description" content="Sistema de relatórios agrícolas para acompanhamento de aplicações e resultados" />
    
    <!-- Força atualização do service worker -->
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
    <meta name="cache-bust" content="2025-07-19-15:25-LAYOUT-FORCE-FIXED" />
    
    <!-- CSP via Meta Tag para garantir que nunca seja revertido -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://unpkg.com https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net; font-src 'self' https://fonts.gstatic.com https://cdn.jsdelivr.net; img-src 'self' data: https: blob: https://*.supabase.co; connect-src 'self' https://*.supabase.co https://*.supabase.io https://api.emailjs.com https://ipapi.co https://ipinfo.io https://ipify.org https://geolocation-db.com https://servicodados.ibge.gov.br https://nominatim.openstreetmap.org; media-src 'self' blob: https://*.supabase.co; worker-src 'self' blob:; child-src 'self' blob:; object-src 'none'; base-uri 'self'; form-action 'self'" />
    
    <!-- PWA Meta Tags -->
    <meta name="theme-color" content="#16a34a" />
    <meta name="msapplication-TileColor" content="#16a34a" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
    <meta name="apple-mobile-web-app-title" content="ResultCrop" />
    <meta name="mobile-web-app-capable" content="yes" />
    <meta name="format-detection" content="telephone=no" />
    
    <!-- iOS Specific Meta Tags -->
    <meta name="apple-touch-fullscreen" content="yes" />
    <meta name="apple-mobile-web-app-orientations" content="portrait" />
    
    <!-- Icons -->
    <link rel="apple-touch-icon" href="/apple-touch-icon.png" sizes="180x180" />
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
    <link rel="mask-icon" href="/favicon.ico" color="#16a34a" />
    <link rel="manifest" href="/manifest.webmanifest" />
    
    <!-- iOS Splash Screens -->
    <link rel="apple-touch-startup-image" href="/apple-splash-2048-2732.png" media="(device-width: 1024px) and (device-height: 1366px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)" />
    <link rel="apple-touch-startup-image" href="/apple-splash-1668-2388.png" media="(device-width: 834px) and (device-height: 1194px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)" />
    <link rel="apple-touch-startup-image" href="/apple-splash-1536-2048.png" media="(device-width: 768px) and (device-height: 1024px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)" />
    <link rel="apple-touch-startup-image" href="/apple-splash-1125-2436.png" media="(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)" />
    <link rel="apple-touch-startup-image" href="/apple-splash-1242-2208.png" media="(device-width: 414px) and (device-height: 736px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)" />
    <link rel="apple-touch-startup-image" href="/apple-splash-750-1334.png" media="(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)" />
    <link rel="apple-touch-startup-image" href="/apple-splash-640-1136.png" media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)" />
    
    <!-- Preconnect para Supabase -->
    <link rel="preconnect" href="https://crhjgygsjssfnmihhjav.supabase.co" />
    
    <!-- 🍎 Safari Mobile Bypass - Redirecionamento Multi-camadas -->
    <!-- BLOCO COMPLETAMENTE REMOVIDO (1ª, 2ª e 3ª camadas de redirecionamento para páginas.dev) -->
    
    <style>
      /* Loading crítico para evitar FOUC */
      #root {
        min-height: 100vh;
        background: #f5f5f5;
      }
      
      /* CSS crítico movido para /src/styles/critical-layout.css para evitar duplicação */
      
      .loading-fallback {
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 100vh;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        color: white;
      }
      
      .loading-content {
        text-align: center;
        padding: 2rem;
      }
      
      .loading-spinner {
        width: 40px;
        height: 40px;
        border: 4px solid rgba(255,255,255,0.3);
        border-top: 4px solid white;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto 1rem;
      }
      
      .loading-progress {
        height: 4px;
        background: rgba(255,255,255,0.2);
        border-radius: 4px;
        margin: 15px auto;
        width: 200px;
        overflow: hidden;
        position: relative;
      }
      
      .loading-progress-bar {
        position: absolute;
        width: 40%;
        height: 100%;
        background: white;
        border-radius: 4px;
        animation: progress 2s infinite ease-in-out;
      }
      
      .loading-message {
        font-size: 14px;
        opacity: 0.8;
        margin-top: 10px;
      }
      
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
      
      @keyframes progress {
        0% { left: -40%; }
        100% { left: 100%; }
      }
      
      .emergency-action {
        background: #dc2626;
        color: white;
        border: none;
        padding: 10px 15px;
        border-radius: 4px;
        margin: 5px;
        cursor: pointer;
        font-size: 14px;
        text-decoration: none;
        display: inline-block;
      }
      
      .emergency-notice {
        background: rgba(220, 38, 38, 0.1);
        border: 1px solid #dc2626;
        color: #dc2626;
        padding: 15px;
        border-radius: 8px;
        margin-top: 20px;
        display: none;
      }
    </style>
    <script type="module" crossorigin src="/assets/index-Bi6PJpg6.js"></script>
    <link rel="modulepreload" crossorigin href="/assets/react-vendor-CTQOF0jv.js">
    <link rel="modulepreload" crossorigin href="/assets/supabase-vendor-DUTjN6MA.js">
    <link rel="modulepreload" crossorigin href="/assets/antd-vendor-Cmk-BxHn.js">
    <link rel="modulepreload" crossorigin href="/assets/charts-vendor-DfOSm2_V.js">
    <link rel="modulepreload" crossorigin href="/assets/utils-vendor-D2ucZu7J.js">
    <link rel="stylesheet" crossorigin href="/assets/index-1755745581978.css">
  </head>
  <body>
    <div id="root">
      <div class="loading-fallback">
        <div class="loading-content">
          <div class="loading-spinner"></div>
          <h2>ResultCrop</h2>
          <p>Carregando aplicação...</p>
          <div class="loading-progress">
            <div class="loading-progress-bar"></div>
          </div>
          <div class="loading-message" id="loadingMessage">Inicializando...</div>
          <div class="emergency-notice" id="emergencyNotice">
            <strong>⚠️ Problemas Detectados</strong>
            <p>Service Workers ou cache problemáticos foram detectados.</p>
            <button onclick="forceServiceWorkerUpdate()" class="emergency-action">🔄 ATUALIZAR SW</button>
            <a href="/safari-cleanup.html" class="emergency-action">🧹 LIMPEZA TOTAL</a>
            <button onclick="window.location.reload()" class="emergency-action">🔄 RECARREGAR</button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Script simplificado de verificação -->
    <script>
      // DETECÇÃO SIMPLES de ambiente
      const isDevelopment = window.location.hostname === 'localhost' || 
                          window.location.hostname === '127.0.0.1' ||
                          window.location.hostname.includes('192.168') ||
                          window.location.port !== '' ||
                          window.location.protocol === 'http:';

      // Se for desenvolvimento, verificar Service Workers problemáticos
      if (isDevelopment && 'serviceWorker' in navigator) {
        navigator.serviceWorker.getRegistrations().then(registrations => {
          if (registrations.length > 0 || navigator.serviceWorker.controller) {
            console.log('⚠️ Service Workers detectados em desenvolvimento');
            
            // Mostrar opção de limpeza depois de 5 segundos se não carregar
            setTimeout(() => {
              const root = document.getElementById('root');
              if (root && root.innerHTML.includes('loading-fallback')) {
                document.getElementById('emergencyNotice').style.display = 'block';
              }
            }, 5000);
          }
        }).catch(error => {
          console.error('Erro ao verificar Service Workers:', error);
        });
      }

      // Mensagens de carregamento
      const loadingMessages = [
        "Inicializando...",
        "Conectando ao servidor...",
        "Carregando dados...",
        "Quase lá..."
      ];
      
      let messageIndex = 0;
      const messageElement = document.getElementById('loadingMessage');
      
      const messageInterval = setInterval(() => {
        messageIndex = (messageIndex + 1) % loadingMessages.length;
        if (messageElement) {
          messageElement.textContent = loadingMessages[messageIndex];
        }
      }, 2000);
      
      // Timeout de segurança para detectar problemas
      setTimeout(() => {
        clearInterval(messageInterval);
        const root = document.getElementById('root');
        
        if (root && root.innerHTML.includes('loading-fallback')) {
          console.error('⚠️ Aplicação não carregou - possível problema com Service Worker');
          
          // Detectar erros 503 específicos
          const hasServiceWorkerErrors = performance.getEntriesByType('navigation')
            .some(entry => entry.responseStatus === 503);
          
          if (hasServiceWorkerErrors || isDevelopment) {
            document.getElementById('emergencyNotice').style.display = 'block';
          }
        }
      }, 15000);

      // Forçar refresh de CSS cached
      function forceCSSRefresh() {
        console.log('🎨 Forçando refresh de CSS...');
        const links = document.querySelectorAll('link[rel="stylesheet"]');
        links.forEach(link => {
          const href = link.href;
          const newHref = href + (href.includes('?') ? '&' : '?') + 'v=' + Date.now();
          link.href = newHref;
        });
      }

      // Detectar cache antigo e forçar refresh automaticamente
      function checkAndRefreshCSS() {
        const currentTime = Date.now();
        const lastRefresh = localStorage.getItem('last_css_refresh');
        const refreshInterval = 5 * 60 * 1000; // 5 minutos
        
        // Cache mais agressivo para mobile
        const isMobile = window.innerWidth <= 768 || /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        const mobileRefreshInterval = isMobile ? 2 * 60 * 1000 : refreshInterval; // 2 minutos para mobile
        
        if (!lastRefresh || currentTime - parseInt(lastRefresh) > mobileRefreshInterval) {
          forceCSSRefresh();
          localStorage.setItem('last_css_refresh', currentTime.toString());
          
          if (isMobile) {
            console.log('📱 Mobile detectado - forçando refresh de CSS a cada 2 minutos');
          }
        }
      }

      // Executar verificação na carga da página
      checkAndRefreshCSS();

      // Layout crítico aplicado via CSS importado no main.tsx
      // Script JavaScript removido para evitar duplicação de responsabilidades

      // Verificação específica para mobile - forçar refresh em caso de layout quebrado
      function checkMobileLayoutAndFix() {
        const isMobile = window.innerWidth <= 768 || /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        
        if (isMobile) {
          console.log('📱 Dispositivo mobile detectado - verificando layout');
          
          // Aguardar carregamento do DOM
          setTimeout(() => {
            // Verificar se classes mobile estão sendo aplicadas
            const testElement = document.createElement('div');
            testElement.className = 'mobile-layout mobile-card';
            testElement.style.position = 'absolute';
            testElement.style.top = '-9999px';
            document.body.appendChild(testElement);
            
            const computedStyle = window.getComputedStyle(testElement);
            const hasMobileStyles = computedStyle.padding === '8px';
            
            document.body.removeChild(testElement);
            
            if (!hasMobileStyles) {
              console.log('⚠️ Estilos mobile não aplicados - forçando refresh CSS');
              forceCSSRefresh();
              
              // Aguardar e verificar novamente
              setTimeout(() => {
                const testElement2 = document.createElement('div');
                testElement2.className = 'mobile-layout';
                testElement2.style.position = 'absolute';
                testElement2.style.top = '-9999px';
                document.body.appendChild(testElement2);
                
                const computedStyle2 = window.getComputedStyle(testElement2);
                const stillBroken = computedStyle2.padding !== '8px';
                
                document.body.removeChild(testElement2);
                
                if (stillBroken) {
                  console.log('🔄 Tentando reload completo da página...');
                  // Em último caso, recarregar a página
                  setTimeout(() => window.location.reload(), 1000);
                }
              }, 2000);
            } else {
              console.log('✅ Layout mobile funcionando corretamente');
            }
          }, 1000);
        }
      }

      // Executar verificação mobile após o carregamento
      if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', checkMobileLayoutAndFix);
      } else {
        checkMobileLayoutAndFix();
      }

      // Função para forçar atualização do service worker
      async function forceServiceWorkerUpdate() {
        console.log('🔄 Forçando atualização do service worker...');
        
        if ('serviceWorker' in navigator) {
          try {
            // Desregistrar todos os service workers
            const registrations = await navigator.serviceWorker.getRegistrations();
            for (const registration of registrations) {
              await registration.unregister();
            }
            
            // Limpar todos os caches
            const cacheNames = await caches.keys();
            for (const cacheName of cacheNames) {
              await caches.delete(cacheName);
            }
            
            // Limpar storages
            localStorage.clear();
            sessionStorage.clear();
            
            console.log('✅ Limpeza concluída, recarregando...');
            window.location.reload();
            
          } catch (error) {
            console.error('❌ Erro na atualização:', error);
            window.location.reload();
          }
        }
      }
      
      // Detectar erros de FetchEvent
      let errorCount = 0;
      let criticalErrors = new Set();
      const originalConsoleError = console.error;
      
      console.error = function(...args) {
        const errorMsg = args.join(' ');
        if (errorMsg.includes('FetchEvent.respondWith') || 
            errorMsg.includes('503 (Service Unavailable)') ||
            errorMsg.includes('Returned response is null')) {
          errorCount++;
          
          // Detectar arquivos com hash antigo
          const hashMatch = errorMsg.match(/(\w+-[A-Za-z0-9]+)\.(js|css)/);
          if (hashMatch) {
            const oldHash = hashMatch[1];
            criticalErrors.add(oldHash);
            console.log('🚨 Hash antigo detectado:', oldHash);
          }
          
          // Para erros críticos, forçar atualização automática após 3 segundos
          if (errorCount >= 3 || criticalErrors.size >= 2) {
            console.log('🚨 ERROS CRÍTICOS DETECTADOS - FORÇANDO ATUALIZAÇÃO AUTOMÁTICA');
            
            setTimeout(() => {
              forceServiceWorkerUpdate();
            }, 3000);
          } else {
            // Mostrar opção de atualização imediatamente para erros críticos
            console.log('🚨 Erro crítico de Service Worker detectado');
            document.getElementById('emergencyNotice').style.display = 'block';
          }
        }
        return originalConsoleError.apply(console, args);
      };
    </script>
    
  </body>
</html>
