import { setupSevereCache } from "./lib/severeCache";
setupSevereCache();

import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { getSiteSettings } from "./hooks/useSiteSettings";

// Load branding settings on startup and handle PWA branding
// Uses 30-day localStorage cache — zero Supabase requests on repeat visits.
let siteFavicon = "/ibec-icon-192.png";
(async () => {
  try {
    const data = await getSiteSettings();
    if (data) {
      siteFavicon = data.favicon_url || "/ibec-icon-192.png";
      const hexToHSL = (hex: string) => {
        const r = parseInt(hex.slice(1, 3), 16) / 255;
        const g = parseInt(hex.slice(3, 5), 16) / 255;
        const b = parseInt(hex.slice(5, 7), 16) / 255;
        const max = Math.max(r, g, b), min = Math.min(r, g, b);
        let h = 0, s = 0;
        const l = (max + min) / 2;
        if (max !== min) {
          const d = max - min;
          s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
          switch (max) {
            case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
            case g: h = ((b - r) / d + 2) / 6; break;
            case b: h = ((r - g) / d + 4) / 6; break;
          }
        }
        return `${Math.round(h * 360)} ${Math.round(s * 100)}% ${Math.round(l * 100)}%`;
      };
      if (data.cor_primaria) document.documentElement.style.setProperty("--primary", hexToHSL(data.cor_primaria));
      if (data.cor_secundaria) document.documentElement.style.setProperty("--accent", hexToHSL(data.cor_secundaria));
      if (data.cor_fundo) document.documentElement.style.setProperty("--background", hexToHSL(data.cor_fundo));
      if (data.favicon_url) {
        let link = document.querySelector("link[rel~='icon']") as HTMLLinkElement;
        if (!link) { link = document.createElement("link"); link.rel = "icon"; document.head.appendChild(link); }
        link.href = data.favicon_url;
        
        // Update manifest dynamically if possible
        let manifestLink = document.querySelector("link[rel='manifest']") as HTMLLinkElement;
        if (manifestLink) {
          const manifest = {
            name: "Igreja Batista em Cristo",
            short_name: "IBEC",
            description: "Igreja Batista em Cristo - O Evangelho Puro & Simples",
            start_url: "/",
            display: "standalone",
            background_color: "#faf3ed",
            theme_color: data.cor_primaria || "#8B0000",
            orientation: "portrait-primary",
            categories: ["religion", "education"],
            lang: "pt-BR",
            icons: [
              { src: data.favicon_url || "/ibec-icon-192.png", sizes: "192x192", type: "image/png", purpose: "any maskable" },
              { src: data.favicon_url || "/ibec-icon-512.png", sizes: "512x512", type: "image/png", purpose: "any maskable" }
            ]
          };
          const stringManifest = JSON.stringify(manifest);
          const base64Manifest = btoa(unescape(encodeURIComponent(stringManifest)));
          manifestLink.href = `data:application/json;base64,${base64Manifest}`;
        }
      }
    }
  } catch (e) { console.error("Failed to load branding:", e); }
})();

// Service Worker Registration for PWA Installability
if ("serviceWorker" in navigator) {
  window.addEventListener("load", () => {
    if (window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1') {
      navigator.serviceWorker.register("/OneSignalSDKWorker.js")
        .then(reg => console.log("SW registered:", reg))
        .catch(err => console.error("SW registration failed:", err));
    } else {
      console.log("Service Worker registration skipped on localhost");
    }
  });
}

// PWA Install Prompt
let deferredPrompt: any = null;

const showPwaBanner = (isIOS = false) => {
  // Check if already installed
  const isStandalone = (window.navigator as any).standalone || window.matchMedia('(display-mode: standalone)').matches;
  if (isStandalone) return;

  // Cleanup existing
  const existing = document.getElementById("pwa-install-banner");
  if (existing) existing.remove();

  const isInIframe = (() => { try { return window.self !== window.top; } catch { return true; } })();
  const isPreviewHost = window.location.hostname.includes("id-preview--") || window.location.hostname.includes("lovableproject.com");
  if (isInIframe || isPreviewHost) return;

  const isMobile = window.innerWidth < 768;
  const banner = document.createElement("div");
  banner.id = "pwa-install-banner";
  
  // Responsive styles
  const desktopStyle = "bottom:24px;right:24px;left:auto;width:370px;";
  const mobileStyle = "bottom:85px;left:16px;right:16px;width:auto;";
  const positionStyle = isMobile ? mobileStyle : desktopStyle;

  // Determine button text and link
  let buttonHtml = '';
  let subtext = 'Acesse rápido na tela inicial';
  
  if (deferredPrompt) {
    buttonHtml = '<button id="pwa-install-btn" style="position:relative;z-index:10;background:white;color:hsl(0,100%,27%);border:none;border-radius:10px;padding:8px 16px;font-weight:700;font-size:12px;cursor:pointer;white-space:nowrap;">Instalar</button>';
  } else {
    // No direct prompt, show tutorial link as a '?' icon on mobile or full text on desktop
    const anchor = isIOS ? '#ios' : (isMobile ? '#android' : '#desktop');
    if (isMobile) {
      buttonHtml = `<a id="pwa-tut-btn" href="/instalar-app${anchor}" style="position:relative;z-index:10;text-decoration:none;background:white;color:hsl(0,100%,27%);border:none;border-radius:50%;width:32px;height:32px;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:16px;cursor:pointer;">?</a>`;
    } else {
      buttonHtml = `<a id="pwa-tut-btn" href="/instalar-app${anchor}" style="position:relative;z-index:10;text-decoration:none;background:white;color:hsl(0,100%,27%);border:none;border-radius:10px;padding:8px 16px;font-weight:700;font-size:12px;cursor:pointer;white-space:nowrap;display:inline-block;">Ver Tutorial</a>`;
    }
    if (isIOS) subtext = 'Toque em compartilhar e "Adicionar à Tela de Início"';
  }

  banner.innerHTML = `
    <div style="position:fixed;${positionStyle}z-index:9999;background:linear-gradient(135deg,hsl(0,100%,22%),hsl(0,100%,35%));color:white;border-radius:20px;padding:16px;display:flex;align-items:center;gap:12px;box-shadow:0 10px 40px rgba(0,0,0,0.4);font-family:Montserrat,sans-serif;border:1px solid rgba(255,255,255,0.1);cursor:pointer;">
      <div style="width:42px;height:42px;background:white;border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0;overflow:hidden;box-shadow:0 4px 10px rgba(0,0,0,0.2);">
        <img src="${siteFavicon}" style="width:100%;height:100%;object-fit:contain;" alt="IBEC" />
      </div>
      <div style="flex:1;min-width:0;">
        <p style="font-weight:800;font-size:13px;margin:0;letter-spacing:-0.01em;">Aplicativo IBEC</p>
        <p style="font-size:10px;opacity:0.8;margin:1px 0 0;line-height:1.2;">${subtext}</p>
      </div>
      <div style="display:flex;align-items:center;gap:8px;">
        ${buttonHtml}
        <button id="pwa-dismiss-btn" style="position:relative;z-index:10;background:rgba(255,255,255,0.15);border:none;color:white;border-radius:50%;width:28px;height:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:14px;">✕</button>
      </div>
    </div>
  `;
  document.body.appendChild(banner);

  const bannerInner = banner.firstElementChild as HTMLElement;

  // Click entire banner to go to tutorial (unless buttons are clicked)
  bannerInner.addEventListener("click", (e) => {
    const target = e.target as HTMLElement;
    if (target.id === "pwa-install-btn" || target.id === "pwa-tut-btn" || target.id === "pwa-dismiss-btn" || target.closest("#pwa-dismiss-btn")) return;
    
    const anchor = isIOS ? '#ios' : (isMobile ? '#android' : '#desktop');
    window.location.href = `/instalar-app${anchor}`;
  });

  if (deferredPrompt) {
    bannerInner.querySelector("#pwa-install-btn")?.addEventListener("click", async (e) => {
      e.preventDefault();
      e.stopPropagation();
      deferredPrompt.prompt();
      const { outcome } = await deferredPrompt.userChoice;
      console.log("PWA install outcome:", outcome);
      deferredPrompt = null;
      banner.remove();
    });
  }

  bannerInner.querySelector("#pwa-dismiss-btn")?.addEventListener("click", (e) => {
    e.preventDefault();
    e.stopPropagation();
    banner.remove();
  });
};

window.addEventListener("beforeinstallprompt", (e) => {
  e.preventDefault();
  deferredPrompt = e;
  setTimeout(() => showPwaBanner(false), 3000);
});

// iOS detection
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !(window as any).MSStream;
const isStandalone = (window.navigator as any).standalone || window.matchMedia('(display-mode: standalone)').matches;

if (isIOS && !isStandalone) {
  setTimeout(() => showPwaBanner(true), 4000);
}

// OneSignal notification prompt - custom banner above header
// Desativado a pedido do usuário
/*
setTimeout(() => {
  const isInIframe = (() => { try { return window.self !== window.top; } catch { return true; } })();
  const isPreviewHost = window.location.hostname.includes("id-preview--") || window.location.hostname.includes("lovableproject.com");
  if (isInIframe || isPreviewHost) return;

  const needsPermission = !("Notification" in window) || window.Notification?.permission === "default";
  
  if (needsPermission) {
    const banner = document.createElement("div");
    banner.id = "notification-banner";
    // Mudar para bottom pra evitar choque com Navbar/Bordas de Notch
    banner.innerHTML = `
      <div style="position:fixed;bottom:20px;left:16px;right:16px;z-index:999999;background:linear-gradient(135deg,hsl(0,100%,15%),hsl(0,100%,27%));color:white;padding:16px;display:flex;flex-direction:row;align-items:center;gap:12px;font-family:Montserrat,sans-serif;border-radius:16px;box-shadow:0 10px 25px rgba(0,0,0,0.3);animation: slideUp 0.5s ease-out;">
        <span style="font-size:24px;">🔔</span>
        <div style="flex:1;">
          <p style="font-size:13px;font-weight:700;margin:0 0 4px 0;">Mantenha-se Atualizado</p>
          <p style="font-size:11px;font-weight:500;margin:0;opacity:0.8;line-height:1.3;">Ative as notificações para devocionais diários e transmissões ao vivo da IBEC!</p>
        </div>
        <div style="display:flex;flex-direction:column;gap:6px;">
          <button id="notif-allow-btn" style="background:white;color:hsl(0,100%,27%);border:none;border-radius:8px;padding:8px 12px;font-weight:800;font-size:11px;cursor:pointer;white-space:nowrap;box-shadow:0 2px 5px rgba(0,0,0,0.1);">Pode Enviar</button>
          <button id="notif-dismiss-btn" style="background:transparent;border:1px solid rgba(255,255,255,0.2);color:rgba(255,255,255,0.7);border-radius:8px;padding:4px;font-weight:600;font-size:9px;cursor:pointer;">Agora Não</button>
        </div>
        <style>@keyframes slideUp { from { transform: translateY(100px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }</style>
      </div>
    `;
    document.body.appendChild(banner);

    document.getElementById("notif-allow-btn")?.addEventListener("click", () => {
      try {
        if ("Notification" in window) {
          Notification.requestPermission().then((permission) => {
            console.log("Status da permissão do navegador:", permission);
            if (permission === "granted") {
              const OSD = (window as any).OneSignalDeferred || [];
              OSD.push(async (OneSignal: any) => {
                if (OneSignal.User && OneSignal.User.PushSubscription) {
                  OneSignal.User.PushSubscription.optIn();
                }
                if (OneSignal.Notifications) {
                  await OneSignal.Notifications.requestPermission();
                } else if (OneSignal.Slidedown) {
                  await OneSignal.Slidedown.promptPush({ force: true });
                }
              });
            }
          });
        }
      } catch (error) {
        console.error("Erro ao tentar acionar o prompt nativo:", error);
      }
      banner.remove();
    });

    document.getElementById("notif-dismiss-btn")?.addEventListener("click", () => {
      banner.remove();
    });
  }
}, 8000);
*/

createRoot(document.getElementById("root")!).render(<App />);

