// PWA - convite de instalacao (Android + iOS) e aviso de nova versao

const INSTALL_DISMISSED_KEY = "perseveranca.installDismissed";
const INSTALL_DELAY_MS = 2500;

function isStandalone() {
  if (typeof window === "undefined") return false;
  if (window.navigator.standalone === true) return true;
  if (typeof window.matchMedia !== "function") return false;
  return window.matchMedia("(display-mode: standalone)").matches;
}

function isIOSDevice() {
  if (typeof navigator === "undefined") return false;
  const ua = navigator.userAgent || "";
  if (/iPad|iPhone|iPod/i.test(ua)) return true;
  return /Macintosh/i.test(ua) && navigator.maxTouchPoints > 1;
}

function readDismissed() {
  try {
    return localStorage.getItem(INSTALL_DISMISSED_KEY) === "1";
  } catch (error) {
    return false;
  }
}

function PwaSheet({ children, onClose }) {
  return (
    <div
      className="absolute inset-0 z-[80] flex items-end"
      style={{ background: "rgba(8,22,26,0.5)" }}
      onClick={onClose}
    >
      <div
        className="w-full rounded-t-3xl px-6 pt-6 pb-8 slide-up"
        style={{ background: "#FAF7F2", boxShadow: "0 -18px 48px rgba(0,0,0,0.22)" }}
        onClick={(e) => e.stopPropagation()}
      >
        {children}
      </div>
    </div>
  );
}

function InstallPrompt() {
  const [dismissed, setDismissed] = React.useState(readDismissed);
  const [deferred, setDeferred] = React.useState(() => window.__installPrompt || null);
  const [visible, setVisible] = React.useState(false);
  const [sheet, setSheet] = React.useState(false);
  const [updatePending, setUpdatePending] = React.useState(() => !!window.__swWaiting);
  const ios = isIOSDevice();

  // Os dois avisos ocupam a mesma faixa da tela: o de atualizacao tem prioridade.
  React.useEffect(() => {
    const handleUpdate = () => setUpdatePending(!!window.__swWaiting);
    window.addEventListener("swupdateready", handleUpdate);
    return () => window.removeEventListener("swupdateready", handleUpdate);
  }, []);

  React.useEffect(() => {
    const handleReady = () => setDeferred(window.__installPrompt || null);
    const handleInstalled = () => {
      setDismissed(true);
      setDeferred(null);
    };

    window.addEventListener("installpromptready", handleReady);
    window.addEventListener("appinstalled", handleInstalled);
    return () => {
      window.removeEventListener("installpromptready", handleReady);
      window.removeEventListener("appinstalled", handleInstalled);
    };
  }, []);

  React.useEffect(() => {
    const timer = window.setTimeout(() => setVisible(true), INSTALL_DELAY_MS);
    return () => window.clearTimeout(timer);
  }, []);

  const close = () => {
    setDismissed(true);
    setSheet(false);
    try {
      localStorage.setItem(INSTALL_DISMISSED_KEY, "1");
    } catch (error) {
      console.warn("Nao foi possivel guardar a dispensa do convite:", error);
    }
  };

  const install = async () => {
    if (!deferred) return;
    try {
      deferred.prompt();
      await deferred.userChoice;
    } catch (error) {
      console.warn("Nao foi possivel abrir o instalador:", error);
    }
    window.__installPrompt = null;
    setDeferred(null);
    close();
  };

  if (isStandalone() || dismissed || !visible || updatePending) return null;
  if (!deferred && !ios) return null;

  return (
    <React.Fragment>
      <div
        className="absolute left-4 right-4 z-[70] slide-up"
        style={{ bottom: "calc(env(safe-area-inset-bottom, 0px) + 96px)" }}
      >
        <div
          className="flex items-center gap-3 rounded-2xl px-4 py-3"
          style={{
            background: "#FAF7F2",
            border: "1px solid #D8CFBF",
            boxShadow: "0 18px 40px -22px rgba(29,28,23,0.55)",
          }}
        >
          <div
            className="flex items-center justify-center rounded-xl shrink-0"
            style={{ width: 40, height: 40, background: "#F5EFE6" }}
          >
            <Icon name="install_mobile" className="text-xl" style={{ color: "#1F3749" }} />
          </div>

          <div className="min-w-0 flex-1">
            <div className="font-headline text-sm leading-tight" style={{ color: "#08161A" }}>
              Instalar na tela inicial
            </div>
            <div className="text-[11px] leading-snug" style={{ color: "#55606A" }}>
              Abre em tela cheia e funciona sem internet.
            </div>
          </div>

          <button
            onClick={ios ? () => setSheet(true) : install}
            className="shrink-0 rounded-full px-4 py-2 text-xs font-bold tracking-wide active:scale-[0.97] transition-transform"
            style={{ background: "#1F3749", color: "#FAF7F2" }}
          >
            Instalar
          </button>

          <button
            onClick={close}
            aria-label="Dispensar"
            className="shrink-0 -mr-1 p-1 active:scale-90 transition-transform"
            style={{ color: "#A39C8C" }}
          >
            <Icon name="close" className="text-lg" />
          </button>
        </div>
      </div>

      {sheet && (
        <PwaSheet onClose={() => setSheet(false)}>
          <div className="font-headline text-xl mb-1" style={{ color: "#08161A" }}>
            Adicionar à Tela de Início
          </div>
          <div className="text-sm mb-5" style={{ color: "#55606A" }}>
            No iPhone, a instalação é feita pelo Safari em dois toques.
          </div>

          {[
            {
              icon: "ios_share",
              text: "Toque no botão Compartilhar, na barra do Safari.",
            },
            {
              icon: "add_box",
              text: 'Role e escolha "Adicionar à Tela de Início".',
            },
            {
              icon: "check_circle",
              text: "Confirme em Adicionar. O ícone aparece junto dos seus apps.",
            },
          ].map((step, index) => (
            <div key={step.icon} className="flex items-start gap-3 mb-4">
              <div
                className="flex items-center justify-center rounded-full shrink-0 text-xs font-bold"
                style={{ width: 24, height: 24, background: "#F5EFE6", color: "#1F3749" }}
              >
                {index + 1}
              </div>
              <div className="flex items-start gap-2 flex-1">
                <Icon name={step.icon} className="text-lg" style={{ color: "#1F3749" }} />
                <span className="text-sm leading-snug" style={{ color: "#08161A" }}>
                  {step.text}
                </span>
              </div>
            </div>
          ))}

          <button
            onClick={close}
            className="w-full py-4 rounded-xl font-headline text-base active:scale-[0.98] transition-transform"
            style={{ background: "#1F3749", color: "#FAF7F2" }}
          >
            Entendi
          </button>
        </PwaSheet>
      )}
    </React.Fragment>
  );
}

function SWUpdateToast() {
  const [waiting, setWaiting] = React.useState(() => window.__swWaiting || null);

  React.useEffect(() => {
    const handler = () => setWaiting(window.__swWaiting || null);
    window.addEventListener("swupdateready", handler);
    return () => window.removeEventListener("swupdateready", handler);
  }, []);

  if (!waiting) return null;

  // Recarrega só quando o novo service worker assumir; senão o antigo responde de novo.
  const apply = () => {
    let reloaded = false;
    const reload = () => {
      if (reloaded) return;
      reloaded = true;
      window.location.reload();
    };
    navigator.serviceWorker.addEventListener("controllerchange", reload, { once: true });
    try {
      waiting.postMessage({ type: "SKIP_WAITING" });
    } catch (error) {
      console.warn("Nao foi possivel ativar a nova versao:", error);
      reload();
    }
    window.setTimeout(reload, 3000);
  };

  return (
    <button
      onClick={apply}
      className="absolute left-4 right-4 z-[75] flex items-center gap-2 rounded-2xl px-4 py-3 slide-up active:scale-[0.99] transition-transform"
      style={{
        bottom: "calc(env(safe-area-inset-bottom, 0px) + 96px)",
        background: "#08161A",
        color: "#F5EFE6",
        boxShadow: "0 18px 40px -22px rgba(29,28,23,0.7)",
      }}
    >
      <Icon name="refresh" className="text-lg" />
      <span className="text-xs font-bold tracking-wide">
        Nova versão disponível — tocar para atualizar
      </span>
    </button>
  );
}

// Estado de instalação compartilhado pelos botões "Instalar o app".
function useInstallPrompt() {
  const [deferred, setDeferred] = React.useState(() => window.__installPrompt || null);
  const [installed, setInstalled] = React.useState(isStandalone);

  React.useEffect(() => {
    const ready = () => setDeferred(window.__installPrompt || null);
    const done = () => {
      setInstalled(true);
      setDeferred(null);
    };
    window.addEventListener("installpromptready", ready);
    window.addEventListener("appinstalled", done);
    return () => {
      window.removeEventListener("installpromptready", ready);
      window.removeEventListener("appinstalled", done);
    };
  }, []);

  const install = async () => {
    if (!deferred) return false;
    try {
      deferred.prompt();
      await deferred.userChoice;
    } catch (error) {
      console.warn("Nao foi possivel abrir o instalador:", error);
    }
    window.__installPrompt = null;
    setDeferred(null);
    return true;
  };

  return { canPrompt: Boolean(deferred), installed, ios: isIOSDevice(), install };
}

// Botão "Instalar app" no padrão do Muscle Builder: abre o instalador do navegador;
// sem instalador disponível, mostra a instrução num balão logo abaixo.
function InstallButton({ dark = false }) {
  const { installed, ios, install } = useInstallPrompt();
  const [help, setHelp] = React.useState(false);
  if (installed) return null;

  const onClick = async () => {
    if (!(await install())) setHelp((v) => !v);
  };
  const texto = ios
    ? "No iPhone: toque em Compartilhar e depois em Adicionar à Tela de Início."
    : "No Chrome: abra o menu ⋮ e escolha Instalar app (ou Adicionar à tela inicial).";

  // O balão se posiciona pelo contêiner "relative" de quem usa o botão (alinhado à direita).
  return (
    <React.Fragment>
      <button
        type="button"
        onClick={onClick}
        aria-expanded={help}
        className="inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-[12px] lg:px-4 lg:py-2 lg:text-[13px] font-bold whitespace-nowrap active:scale-[0.97] transition-transform"
        style={
          dark
            ? { color: "#08161A", background: "linear-gradient(135deg, #C4914E 0%, #EDC877 100%)", boxShadow: "0 8px 22px -10px rgba(237,200,119,0.6)" }
            : { color: "#FAF7F2", background: "linear-gradient(135deg, #0C2530 0%, #1F3749 100%)", boxShadow: "0 8px 22px -10px rgba(8,22,26,0.55)" }
        }
      >
        <span aria-hidden="true">↓</span> Instalar app
      </button>
      {help && (
        <p
          role="status"
          className="absolute right-0 z-20 m-0 rounded-xl px-3.5 py-3 text-[12px] leading-relaxed text-left slide-up"
          style={{
            top: "calc(100% + 10px)",
            width: "min(290px, calc(100vw - 40px))",
            background: dark ? "#0F2630" : "#FFFDF8",
            color: dark ? "rgba(250,247,242,0.82)" : "#55606A",
            border: dark ? "1px solid rgba(237,200,119,0.2)" : "1px solid #D8CFBF",
            boxShadow: "0 16px 40px rgba(8,22,26,0.3)",
          }}
        >
          {texto}
        </p>
      )}
    </React.Fragment>
  );
}

Object.assign(window, { InstallPrompt, SWUpdateToast, InstallButton, useInstallPrompt });
