/* Saints Calendar — PWA install toast + expandable instructions */

const { useState: usePwa, useEffect: useEffectPwa, useRef: useRefPwa } = React;

// Detect platform for tailored instructions
function detectPlatform() {
  if (typeof navigator === "undefined") return "other";
  const ua = navigator.userAgent || "";
  const platform = navigator.platform || "";
  if (/iPad|iPhone|iPod/.test(ua) || (/Mac/.test(platform) && navigator.maxTouchPoints > 1)) return "ios";
  if (/Android/.test(ua)) return "android";
  if (/Mac|Windows|Linux/.test(platform)) return "desktop";
  return "other";
}

function isStandalone() {
  if (typeof window === "undefined") return false;
  return window.matchMedia?.("(display-mode: standalone)").matches ||
         window.navigator.standalone === true;
}

const PWA_DISMISSED_KEY = "sc.pwa.dismissed";

const PwaInstallToast = ({ visible, onClose }) => {
  const [expanded, setExpanded] = usePwa(false);
  const [platform] = usePwa(detectPlatform);
  const [installEvent, setInstallEvent] = usePwa(null);

  useEffectPwa(() => {
    const handler = (e) => {
      e.preventDefault();
      setInstallEvent(e);
    };
    window.addEventListener("beforeinstallprompt", handler);
    return () => window.removeEventListener("beforeinstallprompt", handler);
  }, []);

  useEffectPwa(() => {
    if (visible) {
      // Lock scroll while expanded
      if (expanded) document.body.style.overflow = "hidden";
      else document.body.style.overflow = "";
    } else {
      document.body.style.overflow = "";
      setExpanded(false);
    }
    return () => { document.body.style.overflow = ""; };
  }, [visible, expanded]);

  const handleNativeInstall = async () => {
    if (!installEvent) return;
    installEvent.prompt();
    const { outcome } = await installEvent.userChoice;
    if (outcome === "accepted") {
      onClose();
    }
    setInstallEvent(null);
  };

  const dismiss = () => {
    localStorage.setItem(PWA_DISMISSED_KEY, String(Date.now()));
    setExpanded(false);
    onClose();
  };

  if (!visible) return null;

  const instructions = {
    ios: [
      { step: "Tap the Share button", note: "in the Safari toolbar at the bottom of the screen", glyph: "⎙" },
      { step: "Scroll and tap “Add to Home Screen”", note: "you may need to scroll the actions list", glyph: "⊞" },
      { step: "Tap “Add” in the top-right corner", note: "Saints Calendar will appear on your home screen", glyph: "✓" },
    ],
    android: [
      { step: "Tap the menu", note: "the three-dot icon at the top-right of Chrome", glyph: "⋮" },
      { step: "Choose “Install app” or “Add to Home screen”", note: "Chrome may also offer a banner near the address bar", glyph: "⊞" },
      { step: "Confirm “Install”", note: "the app will open like a native application", glyph: "✓" },
    ],
    desktop: [
      { step: "Look for the install icon in the address bar", note: "a small computer-with-arrow icon on the right side", glyph: "⊞" },
      { step: "Click “Install”", note: "or use the browser menu → Install Saints Calendar", glyph: "✓" },
      { step: "The app opens in its own window", note: "and is added to your Applications / Start menu", glyph: "✦" },
    ],
    other: [
      { step: "Open your browser menu", note: "look for an Install or Add to Home Screen option", glyph: "⋯" },
      { step: "Confirm installation", note: "the app icon will be saved to your device", glyph: "✓" },
    ],
  }[platform];

  const platformLabel = {
    ios: "iPhone & iPad — Safari",
    android: "Android — Chrome",
    desktop: "Desktop — Chrome, Edge, Brave",
    other: "Your device",
  }[platform];

  return (
    <div className={"pwa-toast-root" + (expanded ? " is-expanded" : "")}
         onClick={(e) => { if (expanded && e.target.classList.contains("pwa-toast-root")) setExpanded(false); }}>

      {/* Compact toast (always rendered; hidden when expanded) */}
      <div className={"pwa-toast" + (expanded ? " is-hidden" : "")} role="dialog" aria-label="Install Saints Calendar">
        <div className="pwa-toast-icon">
          <SaintMark size={26} />
        </div>
        <div className="pwa-toast-body">
          <div className="pwa-toast-title">Keep this on your home screen</div>
          <div className="pwa-toast-sub">Saints Calendar can be installed as an app.</div>
        </div>
        <div className="pwa-toast-actions">
          <button className="pwa-toast-learn" onClick={() => setExpanded(true)}>
            Learn more
          </button>
          <button className="pwa-toast-dismiss" onClick={dismiss} aria-label="Dismiss">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
              <path d="M6 6 L18 18 M18 6 L6 18"/>
            </svg>
          </button>
        </div>
      </div>

      {/* Expanded full-screen sheet */}
      <div className={"pwa-sheet" + (expanded ? " is-open" : "")}
           role="dialog" aria-label="Install instructions" aria-hidden={!expanded}>
        <header className="pwa-sheet-head">
          <div className="pwa-sheet-mark"><SaintMark size={36} /></div>
          <h2 className="pwa-sheet-title">Install Saints Calendar</h2>
          <p className="pwa-sheet-lede">
            Read offline · open from your home screen · no browser chrome.
          </p>
          <button className="pwa-sheet-close" onClick={() => setExpanded(false)} aria-label="Close instructions">
            <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
              <path d="M6 6 L18 18 M18 6 L6 18"/>
            </svg>
          </button>
        </header>

        <div className="pwa-sheet-body">
          {installEvent && (
            <div className="pwa-sheet-direct">
              <button className="pwa-direct-btn" onClick={handleNativeInstall}>
                Install now
              </button>
              <p className="pwa-direct-note">Your browser supports a one-tap install.</p>
            </div>
          )}

          <div className="pwa-platform-tag">{platformLabel}</div>

          <ol className="pwa-steps">
            {instructions.map((it, i) => (
              <li key={i} className="pwa-step">
                <div className="pwa-step-num">
                  <span className="pwa-step-glyph">{it.glyph}</span>
                  <span className="pwa-step-idx">{i + 1}</span>
                </div>
                <div className="pwa-step-text">
                  <div className="pwa-step-title">{it.step}</div>
                  <div className="pwa-step-note">{it.note}</div>
                </div>
              </li>
            ))}
          </ol>

          <div className="pwa-sheet-features">
            <div className="pwa-feat">
              <span className="pwa-feat-glyph">❦</span>
              <div>
                <div className="pwa-feat-title">Read anywhere</div>
                <div className="pwa-feat-note">Saints, prayers, and the calendar are cached for offline reference.</div>
              </div>
            </div>
            <div className="pwa-feat">
              <span className="pwa-feat-glyph">☩</span>
              <div>
                <div className="pwa-feat-title">Quiet & private</div>
                <div className="pwa-feat-note">No tracking, no ads. The app simply opens when you need it.</div>
              </div>
            </div>
            <div className="pwa-feat">
              <span className="pwa-feat-glyph">✦</span>
              <div>
                <div className="pwa-feat-title">A daily companion</div>
                <div className="pwa-feat-note">Today's feast on the home screen. Tap and you're there.</div>
              </div>
            </div>
          </div>
        </div>

        <footer className="pwa-sheet-foot">
          <button className="pwa-foot-dismiss" onClick={dismiss}>Maybe later</button>
        </footer>
      </div>
    </div>
  );
};

Object.assign(window, { PwaInstallToast, isStandalone });
