// Faith & Joy — "Get the app" banner at the top of the page.
// iPhone/iPad Safari shows Apple's own Smart App Banner (meta apple-itunes-app in index.html),
// so this one stays hidden there to avoid showing two.
const { useState: useStateB, useEffect: useEffectB, useRef: useRefB } = React;

const FJ_BANNER_KEY = "fj-app-banner-dismissed";
const FJ_BANNER_SNOOZE_MS = 14 * 24 * 60 * 60 * 1000;

function fjShouldShowBanner() {
  const ua = navigator.userAgent || "";
  const isIOS = !/Android/.test(ua) && (/iPhone|iPad|iPod/.test(ua) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1));
  const isIOSSafari = isIOS && /Safari/.test(ua) && !/CriOS|FxiOS|EdgiOS|OPiOS|GSA|FBAN|FBAV|Instagram/.test(ua);
  if (isIOSSafari) return false;
  try {
    const at = Number(localStorage.getItem(FJ_BANNER_KEY));
    if (at && Date.now() - at < FJ_BANNER_SNOOZE_MS) return false;
  } catch (e) {}
  return true;
}

function FJAppBanner({ t }) {
  const [show, setShow] = useStateB(fjShouldShowBanner);
  const ref = useRefB(null);

  // The nav is position:fixed, so push it down by however much of the banner is still on screen.
  useEffectB(() => {
    const root = document.documentElement;
    if (!show) { root.style.setProperty("--fj-banner-offset", "0px"); return; }
    const update = () => {
      const h = ref.current ? ref.current.offsetHeight : 0;
      root.style.setProperty("--fj-banner-offset", Math.max(0, h - window.scrollY) + "px");
    };
    update();
    // Fonts load after first paint and change the banner's height, so watch it directly.
    const ro = window.ResizeObserver && ref.current ? new ResizeObserver(update) : null;
    if (ro) ro.observe(ref.current);
    window.addEventListener("scroll", update, { passive: true });
    window.addEventListener("resize", update);
    return () => {
      if (ro) ro.disconnect();
      window.removeEventListener("scroll", update);
      window.removeEventListener("resize", update);
      root.style.setProperty("--fj-banner-offset", "0px");
    };
  }, [show]);

  if (!show) return null;

  const dismiss = () => {
    setShow(false);
    try { localStorage.setItem(FJ_BANNER_KEY, String(Date.now())); } catch (e) {}
  };

  return (
    <div className="fj-app-banner" ref={ref} role="region" aria-label={t.ui.appStoreAlt}>
      <button className="fj-app-banner-close" onClick={dismiss} aria-label={t.ui.closeBanner || "Close"}>×</button>
      <img className="fj-app-banner-icon" src="assets/apple-touch-icon.png" alt="" width="44" height="44"></img>
      <div className="fj-app-banner-text">
        <strong>Faith &amp; Joy</strong>
        <span>{t.ui.appStoreAlt}</span>
      </div>
      <a className="fj-app-banner-cta" href={window.FJ_APP_STORE_URL} target="_blank" rel="noopener">{t.nav.download}</a>
    </div>
  );
}

window.FJAppBanner = FJAppBanner;
